Esempio n. 1
0
def register_page():
    try:
        form = Registration.Form(request.form)

        if request.method == "POST" and form.validate():
            username = form.username.data
            email = form.email.data
            password = sha256_crypt.encrypt ((str(form.password.data)))
            c, conn = connection(

            x = c.execute("SELECT * FROM users WHERE username = (%s)")
            (thwart (username))

            if int(x)> 0:
                flash("That username is already taken, please choose another")
                return render_template('register.html', form=form)

            else:
                c.execute("INSERT INTO users (username, password, email, tracking") VALUES (%s, %s, %s, %s)
                        (thwart(username), thwart(password), thwart(email), thwart("/introduction-to-python-programming"))

                conn.commit()
                flash("Thanks for registering")
                c.close()
                conn.close()
                gc.collect()

                session('logged_in') = True
                session('username') = username

                return redirect(url_for('dashboard'))
        retun render_template('register.html', form=form)
    except Exception as e:
            return(str(e))
def suma(numero):
    if 'suma' not in session:
        session('suma') = 0
    suma = session('suma')
    suma = suma + int(numero)
    session(suma) = suma
    return str(suma)
Esempio n. 3
0
def getArticleImage():
    image_id = request.args.get('image_id')
    article_id = request.args.get('article_id')
    session = sessionmaker(bind=engine)
    sess = session()
    article = sess.query(Article).filter_by(id=article_id).all()
    sess.close()
    if len(article) != 0:  # 该用户存在即可 同一作者可能存在多篇文章
        auther_open_id = article[0].image
        word = image_id + '_' + article_id + '_' + auther_open_id
        print(word)
        print(os.getcwd())
        # windows
        # command = "dir " + os.getcwd() + " | " + "findstr " + word
        # output = os.popen(command).read()
        # output = ' '.join(output.split()) # 去除output中的多余空格
        # print(output)
        # file = output.split(' ')[3]
        # return send_file(os.getcwd() + '\\' + file, mimetype='image')

        # centOS
        command = "ls " + app.config['UPLOAD_FOLDER'] + " | " + "grep " + word
        output = os.popen(command).read()
        file = output.strip()
        return send_file(app.config['UPLOAD_FOLDER'] + '/' + file,
                         mimetype='image')
Esempio n. 4
0
def get_article():
    article_id = request.args.get('id')
    session = sessionmaker(bind=engine)
    sess = session()
    article = sess.query(Article).get(int(article_id))
    sess.close()
    return jsonify(article.to_dict())
Esempio n. 5
0
def signUp():
    # 处理从微信小程序端传来的注册请求
    result = {}
    if request.method == "POST":
        form = request.json
        print(form)
        session = sessionmaker(bind=engine)
        sess = session()
        if sess.query(Accounts).filter_by(usr_open_id=form['openid']).count() >= 1:
            sess.close()
            result['result'] = 'double sign'
            return jsonify(result)
        else:
            if sess.query(Accounts).filter_by(usr_name=form['author']).count() >= 1:
                sess.close()
                result['result'] = 'same user name'
                return jsonify(result)
            else:
                pwd = generate_password_hash(form['pwd'])
                obj1 = Accounts(usr_name=form['author'], usr_authority=1, usr_open_id=form['openid'], usr_pwd=pwd)
                sess.add(obj1)
                sess.commit()
                sess.close()
                result['result'] = 'success'
                return jsonify(result)
Esempio n. 6
0
def index():
    form=NameForm()
    if form.validate_on_submit():
        session['name']=form.name.data
        form.name.data=''
    return redirect(url_for('index'))
    return render_template('index.html',form=form,name=session('name'))
Esempio n. 7
0
def search():
    POST_TITLE = str(request.form['search'])
    session = sessionmaker(bind=engine)
    s = session()
    result1 = s.query(Manga).filter(Manga.title.like("%%" + POST_TITLE + "%%"))
    result2 = s.query(Manga).filter(Manga.alt_title.like("%%" + POST_TITLE + "%%"))
    strTable = render_template('main.html')
    row = ""
    for row in result1:
        if row:
            title = row.title
            alt_title = row.alt_title
            strRW = "<div class=\"title\">" + str(title) + " - " + str(alt_title) + "</div>"
            strTable = strTable + strRW
    for row in result2:
        if row:
            title = row.title
            alt_title = row.alt_title
            strRW = "<div class=\"title\">" + str(title) + " - " + str(alt_title) + "</div>"
            strTable = strTable + strRW
    if row:
        if row.title:
            strTable = strTable + "</div></body></html>"
            hs = open("./templates/search.html", 'w', encoding="utf-8")
            hs.write(strTable)
            hs.close()
            return render_template('search.html')
    else:
        return render_template('404.html', manga=POST_TITLE)
Esempio n. 8
0
    def store_mysql_by_session_info(data, cls,ty):
        session = sessionmaker(engine)
        mysql_connection = session()
        try:
            # if ty == "policy":
            #     new_model = cls(company_profile_id=data[0],policy=data[1],
            #                     implementation_example=data[2],createAt=data[3],uuid=data[4])
            #
            # elif ty == "evaluation":
            #     new_model = cls(company_profile_id=data[0],Internal_evaluation=data[1],
            #                     external_evaluation=data[2],createAt=data[3],uuid=data[4])
            # elif ty == "stakeholder":
            #     communication_channel = [
            #         {
            #             "man":data[0],
            #             "communication_channel":data[1],
            #             "expectations_demands":data[2],
            #             "response":data[3],
            #             "val":data[4]
            #         }
            #     ]
            #     new_model = cls(company_profile_id=data[0],communication_channel=communication_channel,
            #                     expectations_demands=data[2],response=data[3],createAt=data[5],uuid=data[6])

            if ty == "corporateInfo":
                new_model = mysql_connection.query(cls).filter_by(company_profile_id=data[0]).first()
                if new_model:
                    new_model.cigs_id = data[1]
                    new_model.business_coverage = data[2]
                    new_model.major_business = data[3]
                    new_model.trend = data[4]
                    new_model.total_employee = data[5]
                    new_model.sales_description = data[6]
                    new_model.chairman_word = data[7]
                    new_model.board_of_director = data[8]
                    new_model.esg_structure_info = data[9]
                    new_model.esg_management_policy = data[10]
                    new_model.updateAt = datetime.datetime.now()
                else:
                    new_model = cls(company_profile_id=data[0],cigs_id=data[1],
                                    business_coverage=data[2],major_business=data[3],trend=data[4],total_employee=data[5],
                                    sales_description=data[6],chairman_word=data[7],board_of_director=data[8],
                                    esg_structure_info=data[9],esg_management_policy=data[10],
                                    createAt=data[11],uuid=data[12])

            mysql_connection.add(new_model)
            mysql_connection.commit()
           # print("_____________________________")
            code = 1
        except Exception as e:
           # print(e)
            code = 0
            return code

        mysql_connection.close()
        return code
Esempio n. 9
0
def getInfo():
    openid = request.args.get('openid')
    session = sessionmaker(bind=engine)
    sess = session()
    usr = sess.query(Accounts).filter_by(usr_open_id=openid).all()
    sess.close()
    if len(usr) == 0:
        return json.dumps({'signed': 'false'})
    else:
        return json.dumps({'signed': 'true'})
Esempio n. 10
0
def setLike():
    article_id = request.args.get('article_id')
    like = request.args.get('like')
    session = sessionmaker(bind=engine)
    sess = session()
    article = sess.query(Article).get(int(article_id))
    article.numofLike = int(like)
    sess.add(article)
    sess.commit()
    sess.close()
    return "update success"
Esempio n. 11
0
 def wrapper(*args, **kwargs):
     # 判断用户的登录状态
     user_id = session("user_id")
     # 如果用户是登录的,执行view_func
     if user_id is not None:
         # 将user_id 保存到g对象,在试图函数中通过g 获取保存的数据
         g.user_id = user_id
         return vie_func(*args, **kwargs)
     else:
         # 如果未登录,返回未登录的信息
         return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
Esempio n. 12
0
 def wrapper(*args, **kwargs):
     # 判斷用戶的登入狀態
     user_id = session("user_id")
     # 如果用戶是登入的,執行視圖函數
     if user_id is not None:
         # 將user_id保存於g對象中,在視圖函數中可透過g對象獲得保存數據
         g.user_id = user_id
         return view_func(**args, **kwargs)
     else:
         # 如果未登入,返回未登入的信息
         return jsonify(errno="SESSIONERROR", errmsg="用戶未登入")
Esempio n. 13
0
def getArticleByAuthor():
    age = request.args.get('author_id')
    session = sessionmaker(bind=engine)
    sess = session()
    article_list = []
    articles = sess.query(Article).filter_by().all()
    if len(articles) != 0:
        for article in articles:
            article_list.append(article.to_info())
    else:
        return "no such article"
    return jsonify(article_list)
Esempio n. 14
0
def getArticleByLike():
    session = sessionmaker(bind=engine)
    sess = session()
    articles = sess.query(Article).order_by('numofLike desc').all()
    article_list = []
    sess.close()
    if len(articles) != 0:
        for article in articles:
            article_list.append(article.to_info())
    else:
        return "seems like there is no article"
    return jsonify(article_list)
Esempio n. 15
0
def dbtest2_article(articleid):
    session = sessionmaker(bind=engine)
    sess = session()

    articles = sess.query(Article).all()
    sess.close()

    result = articles[int(articleid)]

    # want to know the quite way to jsonify a class!!!!
    # jsonify the return will be this reverse version
    return jsonify({'title': result.title, 'auther': result.auther, 'number of comment': result.numofComment,
                    'article': result.text})
Esempio n. 16
0
def do_admain_login():

    POST_USERNAME = str(request.form['username'])
    POST_PASSWORD = str(request.form['password'])

    Session = sessionmaker(bind=engine)
    s = session()
    query = s.query(User).filter(User.username.in_([POST_USERNAME]), User.password.in_([POST_PASSWORD]))
    result = query.first()
    if result:
        session['logged_in'] = True
    else:
        flash('wrong password!')
    return home()
Esempio n. 17
0
def do_admain_login():

    POST_USERNAME = str(request.form['username'])
    POST_PASSWORD = str(request.form['password'])

    Session = sessionmaker(bind=engine)
    s = session()
    query = s.query(User).filter(User.username.in_([POST_USERNAME]),
                                 User.password.in_([POST_PASSWORD]))
    result = query.first()
    if result:
        session['logged_in'] = True
    else:
        flash('wrong password!')
    return home()
Esempio n. 18
0
def getArticleByAuthor():
    author_id = request.args.get('author_id')
    session = sessionmaker(bind=engine)
    sess = session()
    article_list = []
    articles = sess.query(Article).filter_by(usr_open_id=author_id).all()
    sess.close()
    if len(articles) != 0:
        for article in articles:
            temp = article.to_info()
            temp['article_id'] = article.article_id
            article_list.append(temp)
    else:
        return "no such article"
    return jsonify(article_list)
Esempio n. 19
0
def process():
    session["error"] = []
    if len(request.form['email']) < 1:
        session["error"].append("Field must be a match")
    # else if email doesn't match regular expression display an "invalid email address" message
    elif not EMAIL_REGEX.match(request.form['email']):
        # We are using the EMAIL_REGEX object that we created and running the "match" method that will return a boolean indicating whether the argument matches.
        session("Invalid Email Address!")
    else:
        flash("Success!")
    info = {
        "email": request.form['email'],
        "first name": request.form['first_name'],
        "last name": request.form['last_name'],
        "password": request.form['password'],
        "confirm password": request.form['confirm_password']
    }
    # len(info["first name"])
    if len(request.form['password']) > 8:
        session["error"].append("Password should be more than 8 characters")
    if len(request.form['first_name']) < 1:
        session["error"].append("Field must not be blank!")
    elif not request.form['first_name'].isalpha():
        session["error"].append("Contents cannot contain numbers!")
    if len(request.form['last_name']) < 1:
        session["error"].append("Field must not be blank!")
    if len(request.form['password']) < 1:
        session["error"].append("Field must not be blank!")
    if len(request.form['confirm_password']) < 1:
        session["error"].append("Field must not be blank!")
    if request.form["password"] == request.form["confirm_password"]:
        session["error"].append(
            "Password and Password Confirmation should match!")
    print session["error"]
    flash(session["error"])
    return redirect("/")
Esempio n. 20
0
def dbtest_add():
    param_id = int(request.args.get('id'))

    session = sessionmaker(bind=engine)
    sess = session()
    # low efficiency!!

    all_accounts = sess.query(Accounts).all()

    # for row in all_accounts:
    #     print(row.name)
    #     print(row.pwd)
    #     print(row.article)
    sess.close()

    return jsonify({'name': all_accounts[param_id].name, 'article': all_accounts[param_id].article})
Esempio n. 21
0
def manga():
    session = sessionmaker(bind=engine)
    s = session()
    result = s.query(Manga).all()
    strTable = render_template('main.html')
    for row in result:
        title = row.title
        alt_title = row.alt_title
        strRW = "<div class=\"title\">" + str(title) + " - " + str(alt_title) + "</div>"
        strTable = strTable + strRW

    strTable = strTable + "</div></body></html>"
    hs = open("./templates/manga.html", 'w', encoding="utf-8")
    hs.write(strTable)
    hs.close()
    return render_template('manga.html')
Esempio n. 22
0
def store_exe(model):
    session = sessionmaker(engine)
    mysql_connection = session()
    try:
        mysql_connection.add(model)
        mysql_connection.commit()
        return 1
    except sqlalchemy.exc.IntegrityError as e:
        #print(e)
        mysql_connection.rollback()
        return 2
    except Exception as e:
        #print(e)
        mysql_connection.rollback()
        return 0
    finally:
        mysql_connection.close()
Esempio n. 23
0
 def _api_request(self, session, url, data=None):
     kwargs = {}
     if data:
         kwargs['data'] = data
         if DEBUG:
             ddata = data.copy()
             for k in ddata:
                 if re.search(r'password', k, re.IGNORECASE):
                     ddata[k] = "XXXXXXXX"
             print("DEBUG: data={0}".format(ddata))
     r = session(url, **kwargs)
     if r.status_code == requests.codes.ok:
         return r.json()
     else:
         print("Request failed: {0}: {1} {2}".format(
             url, r.status_code, r.text))
         return {}
Esempio n. 24
0
def post_session(title):
    event = ems.get_event_title(title)
    if request.method == "POST":
        speaker = request.form['Speaker']
        name = request.form['Name']
        capacitor = int(request.form['Capacitor'])
        Session = session(title=name,
                          speaker=speaker,
                          capacitor=capacitor,
                          seminar_id=event.id)
        try:
            current_user.post_session(Session)
        except (SpeakerError, CapacityError, DupulicationError) as error:
            flash(error.message, 'alart')
            return redirect(url_for('post_session', title=event.title))
        return redirect(url_for('event_details', title=event.title))
    return render_template('Post_Sessions.html', event=event)
Esempio n. 25
0
def getArticleByType():
    type = request.args.get('type')
    openid = request.args.get('openid')
    session = sessionmaker(bind=engine)
    sess = session()
    article_list = []
    articles = sess.query(Article).filter_by(type=type).all()
    for article in articles:
        usrs = sess.query().filter_by()
    sess.close()
    if len(articles) != 0:
        for article in articles:
            temp = article.to_info()
            temp['article_id'] = article.article_id
            article_list.append(temp)
    else:
        return "no such article"
    return jsonify(article_list)
Esempio n. 26
0
def setting():
    session = sessionmaker(bind=engine)
    s = session()
    data = s.query(User).all()
    strTable = render_template('main.html')
    hs = open("./templates/admin.html", 'w', encoding="utf-8")
    hs.write(strTable + "<h1>List User</h1><br>")
    strTable = ""
    for row in data:
        title = row.username
        strRW = "<div>" + str(title) + "</div>"
        strTable = strTable + strRW

    strTable = strTable + "<div class=\"notfound-group\"><div class=\"notfound-child\">"
    strTable = strTable + "</div></body></html>"
    hs.write(strTable)
    hs.close()
    return render_template("admin.html")
def basic_route():
    sqlsession = session()

    wdate = sqlsession.query(times.date).all()
    wtime = sqlsession.query(times.start_time).all()
    etime = sqlsession.query(times.end_time).all()

    checkdate = datetime.now().date()

    if request.method == 'POST':

        convertDate = time.strptime(
            str(datetime.now().date()).replace('-', ' '), "%Y %m %d")
        convertTime = time.strptime(
            str(datetime.now().time()).replace(':', ' ').replace('.', ' '),
            "%H %M %S %f")
        year, month, day = convertDate[0:3]
        hour, minutes = convertTime[3:5]
        convertDate = str(year) + ' ' + str(month) + ' ' + str(day)

        convertTime = str(hour) + ': ' + str(minutes)
        if str(convertDate) not in str(wdate):
            svalue = times(start_time=convertTime, date=convertDate)
            sqlsession.add(svalue)
            sqlsession.commit()
            print('added')
            return redirect(url_for('basic_route'))
        elif str(convertDate) in str(wdate) and str(
                *sqlsession.query(times.start_time)[-1]) != str(None):
            print(str(*sqlsession.query(times.start_time)[-1]))
            print('oh shit')
            svalue = times(end_time=convertTime, date=convertDate)
            sqlsession.add(svalue)
            sqlsession.commit()
            return redirect(url_for('basic_route'))

        else:
            flash('Already added')
            print('nope')
            return redirect(url_for('overview'))
    return render_template('index.html', wdate=wdate, wtime=wtime, etime=etime)
Esempio n. 28
0
def signUp():
    global users
    if request.method == "POST":
        form = request.json
        session = sessionmaker(bind=engine)
        sess = session()
        if sess.query(Accounts).filter_by(
                usr_open_id=form['openid']).count() >= 1:
            abort(500)
        else:
            pwd = generate_password_hash(form['pwd'])
            obj1 = Accounts(usr_name=form['author'],
                            usr_authority=1,
                            usr_open_id=form['openid'],
                            usr_pwd=pwd)
            sess.add(obj1)
            sess.commit()
            sess.close()
            # print(request.json)
            # users[request.json['openid']] = request.json
            # print(users)
            return "signup success"
Esempio n. 29
0
import Models.booking as booking
import Models.timeSlot as timeSlot
import Models.authen as authen
from flask import (
    Blueprint,
    request,
    render_template,
    redirect,
    url_for,
    session,
)
'''
each time a request comes to the server, the script will be run again from the begining
so global variable will be initialized again
but the session will not
g is only alive in one request
session(cookie) is stored in browser
'''

visitorAPI = Blueprint("visitorAPI", __name__, static_folder="./static")
# # the secret key encrypts the session data
# app.secret_key = "Key"


def validate(form):
    # validate imformation
    # if any of the imformation is empty, Then, its not valid
    result = True
    message = ""
    if form["Name"] == "":
        result = False
Esempio n. 30
0
        token = uuid.uuid4().hex
        user.token = token
        session['auth_token'] = token

        db_session.query(User).filter_by(id=user.id) \
            .update({"token": user.token})
        db_session.commit()

        resp = jsonify({'message': "login successful", 'token': token})
        return resp

    return jsonify({'message': 'Bad login'}), 401


@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()

if __name__ == "__main__":
    app.config.from_pyfile('config/config.py')

    if len(sys.argv) == 2:
        conf = sys.argv[1]
        print('Loading additional config %s...', conf)
        app.config.from_pyfile('config/' + conf + '_config.py')

    init_engine(app.config['DATABASE_URI'])
    init_db()
    app.run(host='0.0.0.0')
    session(app)
Esempio n. 31
0
from flask import Flask, render_template, request, session
from flask_session import Session

app = Flask(__name__)

app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
session(app)


@app.route("/", methods=["GET", "POST"])
def python():
    if session.get("notes") is None:
        session["notes"] = []
    if request.method == "POST":
        note = request.form.get("note")
        session["notes"].append(note)
    return render_template("python.html", notes=notes)
Esempio n. 32
0
def printticket():
    """ Prepare to print out the final ticket with all information"""

    if request.method == "GET":
        #TODO: have it redirect to "/"
        return render_template("printticket.html")

    if request.method == "POST":
        # Get the user id
        try:
            userid = session("user_id")
        except:
            return render_template(
                "error.html", error="Sorry, your session has been restarted.")

        # Gather the information from the equipment form.
        try:
            initials = request.form.get(
                "initials").upper()  # Capitalize the initials
            skimake = formatName(request.form.get("skimake"))
            skimodel = formatName(request.form.get("skimodel"))
            skilength = request.form.get("skilength")
            bindmake = formatName(request.form.get("bindmake"))
            bindmodel = formatName(request.form.get("bindmodel"))
            bootmake = formatName(request.form.get("bootmake"))
            bootmodel = formatName(request.form.get("bootmodel"))
            bootcolor = formatName(request.form.get("bootcolor"))
            solelength = request.form.get("solelength")
            mountloc = request.form.get("mountloc")
            notes = request.form.get("notes")

            equipmentinfo = {
                "initials": initials,
                "skimake": skimake,
                "skimodel": skimodel,
                "skilength": skilength,
                "bindmake": bindmake,
                "bindmodel": bindmodel,
                "bootmake": bootmake,
                "bootmodel": bootmodel,
                "bootcolor": bootcolor,
                "solelength": solelength,
                "mountloc": mountloc,
                "notes": notes
            }

            # Store equipment information in the database
            db.execute(
                "INSERT INTO equipmentinfo (userid, intials, skimake, skimodel, skilength, bindmake, bindmodel, bootmake, bootmodel, bootcolor, solelength, mountloc, notes) VALUES (:userid, :intials, :skimake, :skimodel, :skilength, :bindmake, :bindmodel, :bootmake, :bootmodel, :bootcolor, :solelength, :mountloc, :notes)",
                dict(userid=userid,
                     intials=initials,
                     skimake=skimake,
                     skimodel=skimodel,
                     skilength=skilength,
                     bindmake=bindmake,
                     bindmodel=bindmodel,
                     bootmake=bootmake,
                     bootmodel=bootmodel,
                     bootcolor=bootcolor,
                     solelength=solelength,
                     mountloc=mountloc,
                     notes=notes))
            get_db().commit()

        except:
            return render_template(
                "error.html",
                error=
                "We're sorry. There was an error processing equipment information."
            )

        # Grab the customer info
        try:
            values = db.execute("SELECT * FROM contactinfo WHERE id=:userid", {
                userid: userid
            }).fetchall()

            contactinfo = (dict(
                zip([
                    "id", "first", "last", "phone", "email", "address1",
                    "address2", "city", "state", "postal"
                ], values[0])))
        except:
            return render_template(
                "error.html",
                error=
                "We're sorry. There was an error retrieving customer contact info."
            )

        # Grab the skier info
        try:
            values = db.execute("SELECT * FROM skierinfo WHERE id=:userid", {
                userid: userid
            }).fetchall()
            # Select only the most recent iteration by using [-1]
            skierinfo = (dict(
                zip([
                    "id", "first", "last", "phone", "email", "address1",
                    "address2", "city", "state", "postal"
                ], values[-1])))

        except:
            return render_template(
                "error.html",
                error="We're sorry. There was an error retrieving skier info.")

        # Calculate the skier's intitial indicator setting
        try:
            indicator = initialIndicator(solelength, skierinfo["skiercode"])
        except:
            return render_template(
                "error.html",
                error=
                "There was an error calculating the skier's initial indicator value."
            )

        return render_template("printticket.html",
                               contactinfo=contactinfo,
                               skierinfo=skierinfo,
                               equipmentinfo=equipmentinfo,
                               initialindicator=indicator)