示例#1
0
def subscribe():
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    try:
        # amount in cents
        amount = 99

        customer = stripe.Customer.create(email='*****@*****.**',
                                          source=request.form['stripeToken'])

        stripe.Charge.create(customer=customer.id,
                             amount=amount,
                             currency='usd',
                             description='Flask Charge')
        user = helpers.get_user()
        sub = user.subscription
        if not sub:
            helpers.change_user(subscription=True)
            date = datetime.datetime.now() + datetime.timedelta(days=31)
            helpers.change_user(sub_date=date)
        else:
            if datetime.datetime.now() > user.sub_date:
                date = datetime.datetime.now() + datetime.timedelta(days=31)
            else:
                date = user.sub_date + datetime.timedelta(days=31)
            helpers.change_user(sub_date=date)
    except:
        print('subscrption didnt work')
    user = helpers.get_user()
    return render_template('profile.html', user=user)
示例#2
0
def login():
    if not session.get('logged_in'):
        form = forms.LoginForm(request.form)
        if request.method == 'POST':
            username = request.form['username'].lower()
            password = request.form['password']
            if form.validate():
                #if helpers.credentials_valid(username, password):
                session['logged_in'] = True
                session['username'] = username
                return json.dumps({'status': 'Login successful'})
            #return json.dumps({'status': 'Invalid user/pass'})
            return json.dumps({'status': 'Both fields required'})
        return render_template('login.html', form=form)
    user = helpers.get_user()
    sskey = ""
    if 'keyword' in session:
        sskey = session["keyword"]
    simages = ""
    if 'imagePath' in session:
        if session['imagePath'] != "":
            imagePath = session['imagePath']
            print(imagePath)
            if (sskey == ""):
                return render_template("home.html", user=user)
            commonF = Common()
            simages = commonF.sprkSQLReadDFtoList(imagePath, sskey)

            sskey = "You are searching " + sskey
    return render_template('home.html',
                           user=user,
                           searchkey=sskey,
                           hists=simages)
示例#3
0
def subscription():
    if session.get('logged_in'):
        if request.method == 'POST':
            amount = 100

            charged = stripe.Charge.create(amount=amount,
                                           currency='usd',
                                           card=request.form['stripeToken'],
                                           description='Subscription Renewal')

            if charged != None and "id" in charged:
                response = datetime.datetime.now() + datetime.timedelta(
                    days=30)
                response = response.date()
                #save to database
                helpers.change_user(expiry=response)
            else:
                response = 'Failed Renewing'

        user = helpers.get_user()
        fxpairselected = fxpairs[0]
        timeframeselected = timeframes[0]

        return render_template('home.html',
                               user=user,
                               fxpairs=fxpairs,
                               fxpairselected=fxpairselected,
                               timeframes=timeframes,
                               timeframeselected=timeframeselected,
                               date=response,
                               key=stripe_keys['publishable_key'])
    return redirect(url_for('login'))
示例#4
0
def login():
    if session.get("fromPredict"):
        session["fromPredict"] = False
    elif session.get("prediction"):
        session.pop("prediction")
        session.pop("confidence")
        if session.get("imageURL"):
            session.pop("imageURL")
        # if(os.path.exists(session.get('segmentImageURL'))):
        #     os.remove(session.get('segmentImageURL'))
        #     print("File Removed!")

    if not session.get("logged_in"):
        form = forms.LoginForm(request.form)
        if request.method == "POST":
            username = request.form["username"].lower()
            password = request.form["password"]
            if form.validate():
                if helpers.credentials_valid(username, password):
                    session["logged_in"] = True
                    session["username"] = username
                    return json.dumps({"status": "Login successful"})
                return json.dumps({"status": "Invalid user/pass"})
            return json.dumps({"status": "Both fields required"})
        return render_template("login.html", form=form)
    user = helpers.get_user()
    return render_template("home.html", user=user)
示例#5
0
def login():
    if not session.get('logged_in'):
        form = forms.LoginForm(request.form)
        if request.method == 'POST':
            username = request.form['username'].lower()
            password = request.form['password']
            if form.validate():
                if helpers.credentials_valid(username, password):
                    session['logged_in'] = True
                    session['username'] = username
                    return json.dumps({'status': 'Login successful'})
                return json.dumps({'status': 'Invalid user/pass'})
            return json.dumps({'status': 'Both fields required'})
        return render_template('login.html', form=form)
    user = helpers.get_user()
    fxpairselected = fxpairs[0]
    timeframeselected = timeframes[0]

    #CHECK SUBSCRIPTION
    if user.expiry:
        date = user.expiry
    else:
        date = "0001-01-01"
    return render_template('home.html',
                           user=user,
                           fxpairs=fxpairs,
                           fxpairselected=fxpairselected,
                           timeframes=timeframes,
                           timeframeselected=timeframeselected,
                           date=date,
                           key=stripe_keys['publishable_key'])
示例#6
0
def showmembers():
    # custommize your page title / description here
    page_title = 'Show Members'
    page_description = 'Page shows the face images or pictures of the members to be recognized'

    user = helpers.get_user()
    path_for_current_user = KNOWN_IMAGES_PATH + str(user.username) + "/"
    relative_path = KNOWN_IMAGES_RELATIVE_PATH + str(user.username) + "/"

    images = []
    if os.path.exists(path_for_current_user):
        for file in os.listdir(path_for_current_user):
            if file.endswith(".jpg") or file.endswith(
                    ".jpeg") or file.endswith(".png") or file.endswith(
                        ".gif") or file.endswith(".JPG") or file.endswith(
                            ".JPEG") or file.endswith(".PNG") or file.endswith(
                                ".GIF"):
                images.append(os.path.join(relative_path, file))

    cfg.CONTENT_PAGE = 'showmembers'
    # try to match the pages defined in -> pages/
    return render_template('home.html',
                           content=render_template('pages/showmembers.html',
                                                   images=images),
                           CONTENT_PAGE=cfg.CONTENT_PAGE,
                           PAYMENT_STRIPE_DONE=cfg.PAYMENT_STRIPE_DONE)
示例#7
0
def search():
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    stock = request.form.get("search_query")
    user = helpers.get_user()
    sub = user.subscription
    sub_data = user.sub_date
    if sub:
        if datetime.datetime.now() > sub_data:
            helpers.change_user(subscription=False)
            sub = False
    df = eval(stock, sub)
    prices = df['actual'].values.tolist()
    date = []
    for i in range(len(df)):
        date.append(str(df.at[i, 'Date'])[0:10])
    # date = df['Date'].apply(str).values.tolist()
    df.loc[df['action'] == 'HOLD', 'actual'] = None
    df_buy = df.copy()
    df_sell = df.copy()
    df_buy.loc[df_buy['action'] == 'SELL', 'actual'] = None
    prices_buy = df_buy['actual'].values.tolist()
    df_sell.loc[df_sell['action'] == 'BUY', 'actual'] = None
    prices_sell = df_sell['actual'].values.tolist()
    return json.dumps(
        {
            'Date': date,
            'Prices': prices,
            'Buy_Prices': prices_buy,
            'Sell_Prices': prices_sell,
            'Subscription': sub,
            'Return-fAI': "---",
            'Return-holding': "---"
        },
        ignore_nan=True)
示例#8
0
def payment():
    if session.get('logged_in'):
        user = helpers.get_user()
        return render_template('payment.html',
                               key=stripe_keys['publishable_key'],
                               user=user)
    else:
        return redirect(url_for('login'))
示例#9
0
def login_page():
    if session.get('logged_in'):
        user = helpers.get_user()
        try:           
            user.active = True
            return render_template('home.html', user=user)
        except error:
            return render_template('error.html')
示例#10
0
def settings():
    if request.method == 'POST':
        password = request.form['password']
        if password != "":
            password = helpers.hash_password(password)
        email = request.form['email']
        helpers.change_user(password=password, email=email)
        return json.dumps({'status': 'Saved'})
    user = helpers.get_user()
    return render_template('settings.html', user=user)
示例#11
0
文件: app.py 项目: karma0/tafyio
def handle_new_url(message):
    print(f"Received new URL message: {message}")
    if session.get('logged_in'):
        user = helpers.get_user()
        return sio.emit('response', {
            "user": str(user),
            "body": f"{message}",
        }, callback=message_received)
    print("Not logged in...redirecting.")
    return redirect(url_for('login'))
示例#12
0
def settings():
    if session.get('logged_in'):
        if request.method == 'POST':
            password = request.form['password']
            if password != "":
                password = helpers.hash_password(password)
            helpers.change_user(password=password)
            return json.dumps({'status': 'Saved'})
        user = helpers.get_user()
        return render_template('settings.html', user=user)
    return redirect(url_for('login'))
示例#13
0
def homepage():
    if session.get('logged_in'):
        user = helpers.get_user()
        wallets = helpers.get_wallets()

        if request.method == 'POST':
            id = request.form['id']
            helpers.remove_wallet(id)
            return redirect(url_for('homepage'))
        return render_template('home.html', user=user, wallets=wallets)
    return redirect(url_for('login'))
示例#14
0
def settings():
    if session.get("logged_in"):
        if request.method == "POST":
            password = request.form["password"]
            if password != "":
                password = helpers.hash_password(password)
            email = request.form["email"]
            helpers.change_user(password=password, email=email)
            return json.dumps({"status": "Saved"})
        user = helpers.get_user()
        return render_template("settings.html", user=user)
    return redirect(url_for("login"))
示例#15
0
def product():
    if session.get('logged_in'):
        # user logged in
        user = helpers.get_user()
        if user.payed == 0:
            # user must pay    
            return render_template('payment.html', pub_key=pub_key)
        else:
        # user payed already goto product page
            return render_template('product.html', user=user)
    # user needs to login    
    return redirect(url_for('login'))
示例#16
0
def patient(patient_id):
    if session.get("logged_in"):
        user = helpers.get_user()
        patient = helpers.get_patient(int(patient_id))
        if patient.free or user.paid:
            return render_template('chat.html', user=user, patient=patient)
        else:
            return render_template('home.html',
                                   user=user,
                                   patients=helpers.get_patients())
    else:
        return redirect(url_for("login"))
示例#17
0
def settings():
    if session.get('logged_in'):
        if request.method == 'POST':
            # TODO: configure update settings with firebase api
            password = request.form['password']
            if password != "":
                password = helpers.hash_password(password)
            email = request.form['email']
            helpers.change_user(password=password, email=email)
            return json.dumps({'status': 'Saved'})
        user = helpers.get_user()
        return render_template('settings.html', user=user)
    return redirect(url_for('login'))
示例#18
0
def addmember():
    # custommize your page title / description here
    page_title = 'Add a member'
    page_description = 'Add a new member face image in the system'

    user = helpers.get_user()
    #Configuring the upload folder
    # define the name of the directory to be created
    path = KNOWN_IMAGES_PATH + str(user.username) + "/"

    try:
        os.makedirs(path)
    except OSError:
        print("Creation of the directory %s failed" % path)
    else:
        print("Successfully created the directory %s" % path)
    app.config['UPLOAD_FOLDER'] = path

    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            image = face_recognition.load_image_file(
                os.path.join(path, filename))
            face_encoding = face_recognition.face_encodings(image)

            if len(face_encoding) > 0:
                picklefilename = "pickle_" + user.username
                pickle_file = open(os.path.join(path, picklefilename), "ab")
                pickle.dump([filename, face_encoding[0]], pickle_file)
                pickle_file.close()

            return redirect(url_for('uploaded_file', filename=filename))

    cfg.CONTENT_PAGE = 'addmember'

    return render_template('home.html',
                           content=render_template('pages/addmember.html'),
                           CONTENT_PAGE=cfg.CONTENT_PAGE,
                           PAYMENT_STRIPE_DONE=cfg.PAYMENT_STRIPE_DONE)
示例#19
0
def search_api():
    if not session.get('logged_in'):
        return json.dumps({'status': 'Not logged in', 'code': 403})
    else:
        print("request search")
        stock = request.form.get("search_query")
        try:
            print("check Stock", stock)
            df = web.DataReader(
                stock,
                'yahoo',
                start=datetime.datetime(2019, 9, 2),  # start
                end=datetime.datetime(2019, 9, 10))  # end
            print("checked Stock")
            user = helpers.get_user()
            sub = user.subscription
            sub_data = user.sub_date
            if sub:
                if datetime.datetime.now() > sub_data:
                    helpers.change_user(subscription=False)
                    sub = False
            print("evaluation start")
            df = eval(stock, sub)
            print("evaluation end")
            prices = df['actual'].values.tolist()
            date = []
            for i in range(len(df)):
                date.append(str(df.at[i, 'Date'])[0:10])
            # date = df['Date'].apply(str).values.tolist()
            df.loc[df['action'] == 'HOLD', 'actual'] = None
            df_buy = df.copy()
            df_sell = df.copy()
            df_buy.loc[df_buy['action'] == 'SELL', 'actual'] = None
            prices_buy = df_buy['actual'].values.tolist()
            df_sell.loc[df_sell['action'] == 'BUY', 'actual'] = None
            prices_sell = df_sell['actual'].values.tolist()
            return json.dumps(
                {
                    'Stock': stock,
                    'Date': date,
                    'Prices': prices,
                    'Buy_Prices': prices_buy,
                    'Sell_Prices': prices_sell,
                    'Subscription': sub,
                    'Return-fAI': "---",
                    'Return-holding': "---",
                    'code': 301
                },
                ignore_nan=True)
        except:
            return json.dumps({'status': 'Stock not found', 'code': 302})
示例#20
0
def infer():
    # train_length  = request.args.get('train_length', None)
    # predict_length = request.args.get('predict_length', None)
    # print("THIS IS IT - ",train_length,", ",predict_length)
    if session.get('logged_in'):
        if request.method == 'POST':
            password = request.form['password']
            if password != "":
                password = helpers.hash_password(password)
            email = request.form['email']
            helpers.change_user(password=password, email=email)
            return json.dumps({'status': 'Saved'})
        user = helpers.get_user()
        return render_template('viz.html', user=user)
    return redirect(url_for('login'))
示例#21
0
def charge():
    if session.get('logged_in'):
        user = helpers.get_user()
        try:
            amount = 1000  # amount in cents
            customer = stripe.Customer.create(
                email=user.email, source=request.form['stripeToken'])
            stripe.Charge.create(customer=customer.id,
                                 amount=amount,
                                 currency='usd',
                                 description='Discount Optimizer Charge')
            helpers.change_user(payment=helpers.payment_token())
            user.active = True
            return render_template('home.html', user=user)
        except stripe.error.StripeError:
            return render_template('error.html')
示例#22
0
def charge():
    if session.get('logged_in'):
        # Amount in cents
        amount = 500
        current_user = helpers.get_user()
        customer = stripe.Customer.create(email=current_user.email,
                                          source=request.form['stripeToken'])
        charge = stripe.Charge.create(customer=customer.id,
                                      amount=amount,
                                      currency='usd',
                                      description='Service Plan')
        helpers.change_user(paid=1)
        # do anything else, like execute shell command to enable user's service on your app

        return render_template('charge.html', amount=amount)
    return redirect(url_for('login'))
示例#23
0
def settings_api():
    if session.get('logged_in'):
        user = helpers.get_user()
        username = user.username
        email = user.email
        has_subscription = user.subscription
        sub_date = user.sub_date
        return json.dumps({
            'status': 'User data',
            'Username': username,
            'Email': email,
            'Subscription': has_subscription,
            'Date': str(sub_date)[0:10],
            'code': 220
        })
    return json.dumps({'status': 'Not logged in', 'code': 403})
示例#24
0
def login():
    if not session.get('logged_in'):
        form = forms.LoginForm(request.form)
        if request.method == 'POST':
            username = request.form['username'].lower()
            password = request.form['password']
            if form.validate():
                if helpers.credentials_valid(username, password):
                    session['logged_in'] = True
                    session['username'] = username
                    return json.dumps({'status': 'Login successful'})
                return json.dumps({'status': 'Invalid user/pass'})
            return json.dumps({'status': 'Both fields required'})
        return render_template('login.html', form=form)
    user = helpers.get_user()
    return render_template('home.html', user=user)
示例#25
0
文件: app.py 项目: 0x544852/midterms
def login():    

    if not session.get('logged_in'):

        # user not logged in

        form = forms.LoginForm(request.form)

        if request.method == 'POST':

            username = request.form['username'].lower()

            password = request.form['password']

            if form.validate():

                if helpers.credentials_valid(username, password):

                    session['logged_in'] = True

                    session['username'] = username

                    return json.dumps({'status': 'Login successful'})

                return json.dumps({'status': 'Invalid user/pass'})

            return json.dumps({'status': 'Both fields required'})

        return render_template('login.html', form=form)

    # user logged in    

    user = helpers.get_user()

    if user.payed == 0: 

    # user must pay    

        return render_template('payment.html', pub_key=pub_key)

    else:

    # user paid already   

        #return render_template('product.html', user=user)

        return render_template('home.html', user=user)
示例#26
0
def analyse():
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    stock = request.args.get('stock')
    try:
        df = web.DataReader(
            stock,
            'yahoo',
            start=datetime.datetime(2019, 9, 2),  # start
            end=datetime.datetime(2019, 9, 10))  # end
        user = helpers.get_user()
        return render_template('analyse.html',
                               user=user,
                               name=stock,
                               key=api_test_key)
    except:
        return redirect(url_for('home'))
示例#27
0
def charge():
    if session.get('logged_in'):
        user = helpers.get_user()
        try:
            amount = 2000  # amount in cents
            customer = stripe.Customer.create(
                email=user.email, source=request.form['stripeToken'])
            stripe.Charge.create(customer=customer.id,
                                 amount=amount,
                                 currency='usd',
                                 description='Better Doctor Charge')
        except stripe.error.StripeError:
            return render_template('error.html', user=user)
        helpers.change_user(paid=True)

    # This is confusing at the moment because main page is routed by login
    return redirect(url_for('login'))
示例#28
0
def login():
    if not session.get('logged_in'):
        form = forms.LoginForm(request.form)
        if request.method == 'POST':
            username = request.form['username'].lower()
            password = request.form['password']
            if form.validate():
                if helpers.credentials_valid(username, password):
                    session['logged_in'] = True
                    session['username'] = username
                    return json.dumps({'status': 'Login successful'})
                return json.dumps({'status': 'Invalid user/pass'})
            return json.dumps({'status': 'Both fields required'})
        return render_template('login.html', form=form)

    image_names = os.listdir('static/PeopleNotWearingMask')
    user = helpers.get_user()
    return render_template('home.html', user=user, image_names=image_names, curr = customers.customer.capacity)
示例#29
0
def login():
    '''
    Login check
    '''
    if not session.get('logged_in'):
        form = forms.LoginForm(request.form)
        if request.method == 'POST':
            username = request.form['username'].lower()
            password = request.form['password']
            if form.validate():
                if helpers.credentials_valid(username, password):
                    session['logged_in'] = True
                    session['username'] = username
                    return json.dumps({'status': 'Login successful'})
                return json.dumps({'status': 'Invalid user/pass'})
            return json.dumps({'status': 'Both fields required'})
        return render_template('login.html', form=form)
    user = helpers.get_user()
    '''
    Return memems from HDFS

    Common.py is our core libray written by ourselves to use SparkSQL or do inner-text dection 
    Common.py can be seen in .../Flaskex/
    '''

    sskey = ""
    if 'keyword' in session:
        sskey = session["keyword"]
    simages = ""
    if 'imagePath' in session:
        if session['imagePath'] != "":
            imagePath = session['imagePath']
            print(imagePath)
            if (sskey == ""):
                return render_template("home.html", user=user)
            commonF = Common()
            # Common is written by ourselves to run SparkSQL
            simages = commonF.sprkSQLReadDFtoList(imagePath, sskey)
            # sprkSQLReadDFtoList is to get images from hdfs using SparkSQL
            sskey = "You are searching " + sskey
    return render_template('home.html',
                           user=user,
                           searchkey=sskey,
                           hists=simages)
示例#30
0
def my_graph_three():
    user = helpers.get_user()
    start = datetime.datetime(2010, 1, 1)
    end = datetime.datetime.now()
    df = web.DataReader("GOOGL", 'yahoo', start, end)
    dfreg = df.loc[:, ['Adj Close', 'Volume']]
    dfreg['HL_PCT'] = (df['High'] - df['Low']) / df['Close'] * 100.0
    dfreg['PCT_change'] = (df['Close'] - df['Open']) / df['Open'] * 100.0
    dfreg.fillna(value=-99999, inplace=True)
    forecast_out = int(math.ceil(0.01 * len(dfreg)))
    forecast_col = 'Adj Close'
    dfreg['label'] = dfreg[forecast_col].shift(-forecast_out)
    X = np.array(dfreg.drop(['label'], 1))
    X = preprocessing.scale(X)
    X_lately = X[-forecast_out:]
    X = X[:-forecast_out]
    y = np.array(dfreg['label'])
    y = y[:-forecast_out]
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    clfpoly = make_pipeline(PolynomialFeatures(3), linear_model.Ridge())
    clfpoly.fit(X_train, y_train)
    confidencepoly = clfpoly.score(X_test, y_test)
    forecast_set = clfpoly.predict(X_lately)
    dfreg['Forecast'] = np.nan
    last_date = dfreg.iloc[-1].name
    last_unix = last_date
    next_unix = last_unix + datetime.timedelta(days=1)
    for i in forecast_set:
        next_date = next_unix
        next_unix += datetime.timedelta(days=1)
        dfreg.loc[next_date] = [np.nan
                                for _ in range(len(dfreg.columns) - 1)] + [i]
    fig, ax = plt.subplots()
    dfreg['Adj Close'].tail(100).plot()
    dfreg['Forecast'].tail(100).plot()
    plt.legend(loc=4)
    plt.xlabel('Date')
    plt.ylabel('Price')
    canvas = FigureCanvas(fig)
    img = BytesIO()
    fig.savefig(img)
    img.seek(0)
    return send_file(img, mimetype='image/png')