def create_user(user):
    password = hash_password(user["password"])

    sql = "INSERT INTO users(user_name, user_email, user_password, user_address, user_phone, created_by, actions) VALUES ('%s','%s','%s','%s','%s', %d, %d)" % (
        user["user_name"], user["user_email"], password, user["user_address"],
        user["user_phone"], user["created_by"], user["actions"])

    status = 0
    res = ''

    try:
        cursor.execute(sql)
        db.commit()
        status = 200
        res = 'User created successfully'

    except pymysql.Error as e:
        try:
            print("MySQL Error [%d]: %s") % (e.args[0], e.args[1])
            return None
        except IndexError:
            print("MySQL Error: %s") % str(e)
            return None

    except:
        db.rollback()
        status = 401
        res = 'Something went wrong. Try again'

    return res, status
Exemple #2
0
def get_avatar():
    # 获取头像图片数据  上传文件的数据
    data = request.files.get('avatar')
    if not data:
        return jsonify(errno=RET.PARAMERR, errmsg="未传头像")

    try:
        # 读取上传的文件内容,并调用自己封装的方法上传到七牛
        avatar_img_name = img_store(data.read())
    except Exception as e:
        return jsonify(errno=RET.THIRDERR, errmsg="上传失败")

    # 存入数据库
    user_id = g.user_id
    try:
        #  update 方法 第一次添加 第二次可以修改
        UserInfo.query.filter_by(id=user_id).update(
            {"author_url": avatar_img_name})
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    # 通用域名 + 图片名字
    avatar_url = constants.QINIUIMGURL + avatar_img_name
    return jsonify(errno=RET.OK,
                   errmsg="头像上传成功",
                   data={"avatar_url": avatar_url})
Exemple #3
0
def app_register():
    if session.get('loginTag'):
        return redirect(url_for('app_admin'))

    error = None
    form = RegisterForm()
    if form.validate_on_submit():
        try:
            user = User(form.username.data.strip(), form.password.data.strip(),
                        form.email.data.strip(), form.blog.data.strip())
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            db.rollback()
        finally:
            db.session.close()

        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('app_admin'))

    elif form.errors:
        for field_name, errors in form.errors.items():
            for error in errors:
                flash("{0} - {1}".format(field_name, errors), category='error')
    return render_template('register.html', form=form, error=error)
Exemple #4
0
def register(user, address, account):
    userModel = addressModel = None

    try:
        try:
            userModel = UserModel(**user)
            userModel = userDao.save(userModel, autocommit=False)
        except Exception as e:
            print(e)
            if 'Duplicate' in str(e):
                raise ValueError('Username already taken')
            raise ValueError('User informations are not valid')

        try:
            addressModel = AddressModel(**address)
            addressModel = addressDao.save(addressModel, autocommit=False)
        except Exception as e:
            print(e)
            raise ValueError('Address informations are not valid')

        try:
            accountModel = AccountModel(**account)
            accountModel.id_User = userModel.id
            accountModel.id_Address = addressModel.id
            accountDao.save(accountModel, autocommit=False)
        except Exception as e:
            print(e)
            raise ValueError('Account informations are not valid')

        db.commit()
        return userDao.getById(userModel.id)

    except Exception as e:
        db.rollback()
        raise e
Exemple #5
0
def admin_album():

    if request.method == 'POST':

        album_name = request.form.get('album_name')
        album_state = request.form.get('album_state') or '1'
        album_desc = request.form.get('album_desc')

        if not album_name:
            return make_response(jsonify({"code": 1, "message": "请填写相册名称!"}))
        try:
            db.session.add(Album(album_name=album_name, album_desc=album_desc))
            db.session.commit()
        except Exception:
            db.rollback()
            return make_response(
                jsonify({
                    "code": 1,
                    "message": "新增失败,请联系管理员!"
                }))
        finally:
            db.session.close()
        return make_response(jsonify({"code": 0, "message": "新建成功!"}))

    albums = db.session.query(
        Album.album_id, Album.album_name,
        Album.album_slt).filter(Album.album_status == '1').all()
    return render_template('album/index.html', albums=albums)
def create_product(product):
    sql = "INSERT INTO products (product_name, product_description, product_price, product_qty, created_by, actions) VALUES('%s','%s','%8.2f','%d','%d', '%d')" % (
        product["product_name"], product["product_description"],
        product["product_price"], product["product_qty"],
        product["created_by"], product["actions"])
    print(sql)
    status = 0
    res = ''

    try:
        cursor.execute(sql)
        db.commit()
        status = 200
        res = 'Product created successfully'

    except pymysql.Error as e:
        try:
            print("MySQL Error" + str(e))
            return None
        except IndexError:
            print("MySQL Error: %s") % str(e)
            return None

    except:
        db.rollback()
        status = 401
        res = 'Something went wrong. Try again'

    return res, status
Exemple #7
0
def user_fb_login():
    # POST: Process response from external Fitbit server.
    if request.method == "POST":
        # Extract the Fitbit token and username from the response data.
        fb_token, username = complete_fb_login(request.data)

        # If the username wasn't saved, return to the original PowerToken login
        # page.
        if username is None:
            return redirect(url_for("user_login", error="Invalid username"))

        # Get the user with that username from the database.
        user = User.query.filter_by(username=username).first()

        # If the user with that username isn't in the database for whatever
        # reason, go back to the PowerToken login page.
        if user is None:
            return redirect(url_for("user_login", error="Invalid user"))

        # If everything is okay so far, add the Fitbit token to the database.
        user.fb_token = fb_token

        try:
            db.session.commit()
        except:
            db.rollback()

        # This code will never be called but must be present.
        return render_template("user_home.html", username=username)

    # GET: Render Fitbit page, which redirects to external login.
    elif request.method == "GET":
        username = request.args.get("username")
        return render_template("user_fb_login.html", username=username)
Exemple #8
0
def auth_delete_node():

    nid = request.form.get('nid')
    if not nid:
        return make_response(jsonify({"code": 1, "message": "参数传递错误!"}))

    query = db.session.query(func.count(
        Module.module_id)).filter(Module.module_parent == nid).scalar()

    if query:
        return make_response(jsonify({"code": 1, "message": "请删除节点下面的子节点先!"}))

    try:
        db.session.query(RoleAndModule).filter(
            RoleAndModule.module_id == nid).delete()
        db.session.query(Module).filter(Module.module_id == nid).delete()
        db.session.commit()
        return make_response(jsonify({"code": 0, "message": "删除成功!"}))
    except Exception:
        db.rollback()
        return make_response(jsonify({
            "code": 1,
            "message": "数据库执行失败,请联系管理员!"
        }))
    finally:
        db.session.close()
Exemple #9
0
def signup():
    '''
    Specify what happens when the signup link is accessed.
    If signup is successful, the user will be added into database, logged in and redirected to the myphotos page.
    If signup failed, an error page with proper messages will be redirected to.

    The users table in the database have the following columns:
        userid, username, salt, hhash, count (i.e. # of images the user uploaded)

    userid is unique, as it will be automatically incremented as new entry (i.e. new user) is added to the table.
    username is also set to be unique, so addition of duplicate username will cause an exception to be raised.
    salt value will be per-user.
    hhash will be the encrypted version of the password user input.
    '''

    utils.record_requests()
    # If user is logged in, access to the login page will direct user to myphotos
    if (current_user.is_authenticated):
        return redirect(url_for('myphotos'))
    if request.method == 'POST':
        # read user input to the form
        username = request.form.get('username')
        password = request.form.get('password')
        # Do not allow empty username and/or password
        if username == '' or password == '':
            return render_template('error.html',
                                   error="Empty field(s) is not allowed.")
        # encrpt the plain text password
        salt = uuid.uuid4().hex
        hhash = hashlib.sha256(password.encode() + salt.encode()).hexdigest()
        # access the database
        cur = db.cursor()
        # insert user-input username and password into the users table
        try:
            cur.execute(
                "INSERT INTO users (username, salt, hhash, count) VALUES ('%s', '%s', '%s', '%d');"
                % (username, salt, hhash, 0))
        except Exception as e:
            db.rollback()
            cur.close()
            # exception caused by duplicate username
            if (e.args[0] == 1062):
                e = "Username has already been registered!"
            # exception caused by username being too long (limit is 50 characters)
            elif (e.args[0] == 1406):
                e = "Username is too long!"
            # handle any other database errors
            return render_template('error.html', error=e)
        db.commit()
        # Now that signup complete successfully, log in the newly registered user with flask-login
        user = User.get(username)
        cur.close()
        login_user(user)
        # flash a message on website to let users know they have succesfully signed up and logged in.
        flash(
            "Your account is created successfully and you are now logged in! Start by uploading your first photo."
        )
        return redirect(url_for('myphotos'))
    return render_template('signup.html')
Exemple #10
0
def login():
    form = LoginForm()
    if request.method == 'GET':
        return render_template("base.html", title='login', form=form)
    else:
        db = pymysql.connect(
            host='database-1.clr3d8nnckz4.us-east-2.rds.amazonaws.com',
            user='******',
            password='******',
            port=3306,
            db='chatbot')
        cursor = db.cursor()
        sql = [
            "SELECT password,name,email from student where id=%s",
            "SELECT password,name,email from staff where id=%s"
        ]
        if form.validate_on_submit():
            id = form.id.data
            print(id)
            password = form.password.data
            SorT = form.SorT.data
            if SorT == 1:
                cursor.execute(sql[0], id)
                result = cursor.fetchall()
                if len(result) != 0:
                    ((results, user, email), ) = result
                    print(results)
                    print(password)
                    if check_password_hash(results, password):
                        db.commit()
                        db.close()
                        info = [id, user, email, 's']
                        print(info)
                        return render_template("index_student.html", info=info)

            else:
                cursor.execute(sql[1], id)
                result = cursor.fetchall()
                if len(result) != 0:
                    ((results, user, email), ) = result
                    print(results)
                    print(password)
                    if check_password_hash(results, password):
                        db.commit()
                        db.close()
                        info = [id, user, email, 't']
                        print(info)
                        return render_template("index_teacher.html", info=info)
        else:
            print('******')
        db.rollback()
        db.close()
        flash(
            u'Sorry, your account or password was incorrect. Please double-check.',
            'error')
        return redirect(url_for('login'))
Exemple #11
0
def display(imname=None, cvname=None):
    '''
    Specify what happens when the display link is accessed.
    Only logged in users can access this link; others will be redirected to the login page.

    This webpage displays an original photo and its opencv processed version side by side.
    This webpage can be accessedd in 3 ways: 1) after successful upload; 2) after clicking on thumbnails on myphotos page; 3) url.

    For 2), the redirect is handled in html, which makes it necessary to have the two extra variables in the url

    For 3), user might try to access others photos by guessing the image names to compose the url. 
    We specifically check the owner of the images about to be displayed to prevent this illegal access from happening.
    '''

    utils.record_requests()

    # recover namebase and extension from imname
    namebase, extension = imname.rsplit('.', 1)
    # make sure the imname and cvname correspond to each other
    if (namebase + '_cv' != cvname.rsplit('.', 1)[0]):
        return render_template(
            'error.html',
            error=
            'Wrong access! Please display photos by choosing from "My Photos" page.'
        )
    # access database
    cur = db.cursor()
    # retrieve info about the user who uploaded this photo
    try:
        cur.execute(
            "SELECT userid FROM images WHERE namebase = '%s' AND extension = '%s';"
            % (namebase, extension))
    except Exception:
        db.rollback()
        cur.close()
        return render_template('error.html')
    userid = cur.fetchone()[0]
    cur.close()
    # check if the photo's owner matches current user
    if (userid == None) or (userid != current_user.userid):
        return render_template(
            'error.html',
            error=
            'Wrong access! Please display photos by choosing from "My Photos" page.'
        )

    presigned_urls = []
    try:
        im_url = generate_presigned_url(imname)
        cv_url = generate_presigned_url(cvname)
        data = [im_url, cv_url]
        presigned_urls.append(data)
    except Exception:
        return render_template('error.html', error="cannot read images")

    return render_template('display.html', im_url=im_url, cv_url=cv_url)
Exemple #12
0
def sign_in():
    form = RegisterForm()
    if request.method == 'GET':
        return render_template("register.html", title='register', form=form)
    else:
        db = pymysql.connect(
            host='database-1.clr3d8nnckz4.us-east-2.rds.amazonaws.com',
            user='******',
            password='******',
            port=3306,
            db='chatbot')
        cursor = db.cursor()
        sql = [
            "INSERT INTO student(id,email,password,name) VALUES (%s,%s,%s,%s)",
            "INSERT INTO staff(id,email,password,name) VALUES (%s,%s,%s,%s)"
        ]
        if form.validate_on_submit():
            id = form.id.data
            name = form.name.data
            email = form.email.data
            password = form.password.data
            SorT = form.SorT.data
            password = generate_password_hash(password)
            if SorT == 1:
                cursor.execute("SELECT * from student where id=%s", id)
                result = cursor.fetchall()
                if len(result) != 0:
                    flash(
                        'Registration failed, zID has been registered, please log in directly.',
                        'error')
                    return render_template("register.html",
                                           title='register',
                                           form=form)
                else:
                    cursor.execute(sql[0], (id, email, password, name))
            else:
                cursor.execute("SELECT * from staff where id=%s", id)
                result = cursor.fetchall()
                if len(result) != 0:
                    flash(
                        'Registration failed, zID has been registered, please log in directly.',
                        'error')
                    return render_template("register.html",
                                           title='register',
                                           form=form)
                else:
                    cursor.execute(sql[1], (id, email, password, name))
            db.commit()
            db.close()
            # flash('Congratulations, your register are success.', 'info')
            return redirect(url_for('login'))
        db.rollback()
        db.close()
        flash('Sorry, your register not success, please try again.', 'error')
        return render_template("register.html", title='register', form=form)
def generic_database_insertion_multiple(query, params):
    try:
        for key, value in params.items():
            value = str(value).replace("'", "''")
            query = query.replace(key, str(value))
    except:
        pass

    try:
        with conn.cursor() as cursor:
            cursor.execute(query)
            conn.commit()
            return 'thread complete'
    except psycopg2.InterfaceError:
        conn.rollback()
    except psycopg2.InternalError:
        conn.rollback()
Exemple #14
0
def set_user_name():
    '''修改用户名'''
    user_id = g.user_id
    data = json.loads(request.get_data())
    if not data:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")
    name = data['name']
    # 跟新数据库中的用户名
    try:
        UserInfo.query.filter_by(id=user_id).update({"user_name": name})
        db.session.commit()
        session["name"] = name
    except Exception as e:
        logging.error(e)
        db.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据错误")
    return jsonify(errno=RET.OK, errmsg="ok")
def edit_product(data):
    sql = "SELECT * FROM products WHERE product_id = %d" % data["product_id"]
    print(sql)
    status = 0
    res = ''
    try:
        cursor.execute(sql)
        result = cursor.fetchone()
        print(type(result[6]))
        if result[6] == 2 or result[6] == 3 or result[6] == 6 or result[
                6] == 7 or result[6] == 15:
            sql = "UPDATE products SET product_name = '%s',product_description = '%s',product_price = '%8.2f', product_qty = '%d', created_by = '%d', actions = '%d' WHERE product_id = %d" % (
                data["product_name"], data["product_description"],
                data["product_price"], data["product_qty"], data["created_by"],
                data["actions"], data["product_id"])
            print(sql)
            status = 0
            res = ''

            try:
                cursor.execute(sql)
                db.commit()
                status = 200
                res = 'Product updated successfully'

            except pymysql.Error as e:
                try:
                    print("MySQL Error" + str(e))
                    return None
                except IndexError:
                    print("MySQL Error: %s") % str(e)
                    return None

            except:
                db.rollback()
                status = 401
                res = 'Something went wrong. Try again'

        else:
            status = 201
            res = "Not authorized"

    except:
        print("Error: unable to fetch data")

    return res, status
Exemple #16
0
def add():
    """
    "   add question based on [name]
    """
    try:
        data = request.json
        if data is None:
            return response_error(MESSAGE.INVALID_PARAMETER,
                                  CODE.INVALID_PARAMETER)

        name = data['name']
        question = Question(name=name, )
        db.session.add(question)
        db.session.commit()

        return response_ok(question.to_json())
    except Exception as ex:
        db.rollback()
        return response_error(str(ex))
def add():
    """
    "   add business model based on [name]
    """
    try:
        data = request.json
        if data is None:
            return response_error(MESSAGE.INVALID_PARAMETER,
                                  CODE.INVALID_PARAMETER)

        name = data['name']
        bm = BusinessModel(name=name, )
        db.session.add(bm)
        db.session.commit()

        return response_ok(bm.to_json())
    except Exception as ex:
        db.rollback()
        return response_error(str(ex))
Exemple #18
0
def changegroupid():
    if current_user.perm == Permission.ADMIN:
        id = request.args['id']
        groupid = request.args['newgroup']
        if len(groupid) != 6:
            flash('群组长度不对,请确认为六位!')
            return 'fail'
        user = Students.query.filter_by(id=id).first()
        print(user.fk_tid)
        if user is not None and user.fk_tid != groupid:
            user.fk_tid = groupid
            db.session.add(user)
            try:
                db.session.commit()
            except:
                db.rollback()
            flash('修改成功!')
            return 'ok'
        else:
            flash('修改失败(groupid)')
            return 'fail'
def generic_database_update(query, params):
    try:
        for key, value in params.items():
            value = str(value).replace("'", "''")
            query = query.replace(key, str(value))
    except:
        pass

    try:
        with conn.cursor() as cursor:
            cursor.execute(query)
            res = cursor.fetchone()
            conn.commit()
            if res is not None:
                return res[0]
            else:
                return 0
    except psycopg2.InterfaceError:
        conn.rollback()
    except psycopg2.InternalError:
        conn.rollback()
Exemple #20
0
def save_house_img(house_id):
    try:
        house = HouseInfo.query.filter_by(id=house_id).first()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    # 判断房屋是否存在
    if not house:
        return jsonify(errno=RET.DATAERR, errmsg="房屋不存在")

    # request.files.get("house_image") 是一个文件类   ready() 党法读取数据
    img_data = request.files.get("house_image").read()
    if not all([house_id, img_data]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    # 读取上传的文件内容,并调用自己封装的方法上传到七牛
    try:
        image_name = img_store(img_data)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传失败")

    # 图片名存入数据库
    house_pic = HousePic(house_id=house_id, img_url=image_name)
    db.session.add(house_pic)

    # 如果房屋主图片未设置 设置主图
    if house.index_image_url == '':
        house.index_image_url = image_name
        db.session.add(house)

    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据存储异常")

    url = constants.QINIUIMGURL + image_name
    return jsonify(errno=RET.OK, errmsg="ok", data={"url": url})
Exemple #21
0
def rel_auth():
    '''用户实名认证'''
    user_id = g.user_id
    user = UserInfo.query.filter_by(id=user_id).first()
    if request.method == 'POST':
        data = json.loads(request.get_data())
        real_name = data.get('real_name')
        id_card = data.get('id_card')
        # 保存数据库
        try:
            #只有当 真是姓名和省份在好为空才能添加
            UserInfo.query.filter_by(id=user_id, real_name='',
                                     id_card='').update({
                                         'real_name': real_name,
                                         "id_card": id_card
                                     })
            db.session.commit()
        except Exception as e:
            logging.error(e)
            db.rollback()
            return jsonify(errno=RET.DBERR, errmsg='数据错误')
    return jsonify(errno=RET.OK, errmsg='ok', data=user.get_dict())
Exemple #22
0
def api_register():
    '''
    API especially for test
    '''

    username = request.form.get('username')
    password = request.form.get('password')

    if username == '' or password == '':
        # Forbidden
        return jsonify("Empty field(s) is not allowed."), 403

    salt = uuid.uuid4().hex
    hhash = hashlib.sha256(password.encode() + salt.encode()).hexdigest()
    cur = db.cursor()
    try:
        cur.execute(
            "INSERT INTO users (username, salt, hhash, count) VALUES ('%s', '%s', '%s', '%d');"
            % (username, salt, hhash, 0))
    except Exception as e:
        db.rollback()
        cur.close()
        if (e.args[0] == 1062):
            e = "Username has already been registered!"
            # Conflict
            return jsonify(e), 409
        elif (e.args[0] == 1406):
            # Forbidden
            e = "Username is too long!"
            return jsonify(e), 403
    db.commit()
    user = User.get(username)
    if (user == None):
        # Internal server error
        return jsonify("Database error; cannot add user"), 500
    cur.close()
    login_user(user)
    return jsonify("Successfully registered"), 200
def generic_database_connect(query, params):
    try:
        for key, value in params.items():
            value = str(value).replace("'", "''")
            query = query.replace(key, str(value))
    except:
        pass

    if "update" in query:
        print(query)
    try:
        with conn.cursor() as cursor:
            cursor.execute(query)
            conn.commit()
            return [
                dict((cursor.description[i][0], value)
                     for i, value in enumerate(row))
                for row in cursor.fetchall()
            ]
    except psycopg2.InterfaceError:
        conn.rollback()
    except psycopg2.InternalError:
        conn.rollback()
def selectDApply():
    db = pymysql.connect("127.0.0.1", "root", "638436", "adms")
    cursor = db.cursor()
    dapply = "select * from dapplication"  # 获得诊断申请列表查询语句 where da_uid='" + username + "'"
    try:
        # 执行sql语句
        cursor.execute(dapply)
        da_re = cursor.fetchall()
        da = ()
        for i in da_re:
            if i[4] == "申请中":
                i = i + ('/Allow', 'btn btn-success', 'submit', '批准')
            da += ((i),)
        print(da)
        db.commit()
    except:
        # 如果发生错误则回滚
        traceback.print_exc()
        db.rollback()
        msg = "服务器错误!"

    # 关闭数据库连接
    db.close()
Exemple #25
0
def update_anime_db(page=1):
    last_page = 322
    if page == last_page:
        print('complete')
        return
    url = "https://api.jikan.moe/v3/top/anime/" + str(page)
    time.sleep(4)
    response = requests.get(url)
    if response.status_code == 200:
        json = response.json()
        top = json.get('top')
        for i in range(50):
            this_mal_id = top[i]['mal_id']
            exists = MAL_Database.query.filter_by(mal_id=this_mal_id).first()
            if exists is None:
                anime = MAL_Database(rank=top[i]['rank'],
                                     mal_id=this_mal_id,
                                     title=top[i]['title'],
                                     image_url=top[i]['image_url'],
                                     episodes=top[i]['episodes'],
                                     mal_score=str(top[i]['score']),
                                     mal_url=top[i]['url'],
                                     start_date=top[i]['start_date'],
                                     end_date=top[i]['end_date'],
                                     anime_type=top[i]['type'],
                                     members=top[i]['members'])
                try:
                    db.session.add(anime)
                    db.session.commit()
                except Exception as e:
                    print("rolling back")
                    db.rollback()
        page = page + 1
        update_anime_db(page)
    else:
        print('finished or didnt get response status code is %s',
              response.status_code)
Exemple #26
0
def register():
    """
    "   user register based on [name], [email] and [password]
    """
    try:
        data = request.json
        if data is None:
            return response_error(MESSAGE.INVALID_PARAMETER,
                                  CODE.INVALID_PARAMETER)

        email = data['email']
        name = data['name']
        password = data['password']

        if is_valid_email(email) == False:
            return response_error(MESSAGE.INVALID_EMAIL, CODE.INVALID_EMAIL)

        user = User.find_by_email(email)
        if user is not None:
            return response_error(MESSAGE.USER_HAS_EMAIL_EXIST_ALREADY,
                                  CODE.USER_HAS_EMAIL_EXIST_ALREADY)

        confirm = hashlib.md5('{}{}'.format(password.strip(),
                                            'appscyclone')).hexdigest()
        user = User(
            name=name,
            email=email,
            password=confirm,
        )
        db.session.add(user)
        db.session.commit()

        return response_ok(user.to_json())
    except Exception as ex:
        db.rollback()
        return response_error(str(ex))
Exemple #27
0
    def save_url(self, url):
        uniq_attempt = self.MAX_ATTEMPTS

        while uniq_attempt > 0:
            codes = [
                self._generate(self.CODE_LENGTH)
                for _ in range(self.NUM_TEMP_CODES)
            ]
            existing = [
                l.short_code for l in Link.select(Link.short_code).where(
                    Link.short_code.in_(codes))
            ]
            codes = [c for c in codes if c not in existing]
            try:
                Link.insert(short_code=codes[0], original_url=url).execute()
                return codes[0]
            except db_err.UniqueViolation:
                db.rollback()
                uniq_attempt -= 1
            except db_err.DatabaseError as err:
                db.rollback()
                raise RuntimeError("Error saving a link record.", exc_info=err)

        raise ShortCodeGenerationFailure
Exemple #28
0
def api_upload():
    '''
    API especially for load_generator to test
    '''

    # check user info and login first
    username = request.form.get('username')
    password = request.form.get('password')
    user = User.get(username)
    if (user == None):
        # unauthorized
        return jsonify("Username does not exist!"), 401
    veryfied_password = hashlib.sha256(password.encode() +
                                       user.salt.encode()).hexdigest()
    if (veryfied_password == user.hhash):
        login_user(user)
    else:
        # unauthorized
        return jsonify("Incorrect password!"), 401

    # get info about the user-uploaded image
    try:
        file = request.files['file']
    # Do not allow images bigger than 10M
    except RequestEntityTooLarge:
        # forbidden
        return jsonify("Image exceeds size limit (10M)."), 403
    # Do not allow empty upload
    if file.filename == '':
        # forbidden
        return jsonify("No image selected."), 403
    # Get a secure version of the filenmae
    filename = secure_filename(file.filename)
    # Separate filename and extension for easier name composition for original, thumbnail and opencv processed version
    filename, extension = filename.rsplit('.', 1)

    # access database
    cur = db.cursor()
    # read count from table users for naming the uploaded image
    try:
        cur.execute("SELECT count FROM users WHERE userid = '%d';" %
                    (current_user.userid))
    except Exception:
        cur.close()
        # internal server error
        return jsonify("Database error: cannot read column `count`"), 500
    count = cur.fetchone()
    if (count == None):
        return jsonify("Database error: cannot read column `count`"), 500
    count = count[0]

    # compose the namebase
    namebase = '_'.join([filename, str(current_user.userid), str(count)])

    # if successfully uploadded, update count in users table
    try:
        cur.execute("UPDATE users SET count = '%d' WHERE userid = '%d';" %
                    (count + 1, current_user.userid))
    except Exception:
        db.rollback()
        cur.close()
        return jsonify("Database error: cannot update column `count`"), 500

    # insert new entry (i.e. new image) into the users table
    try:
        cur.execute(
            "INSERT INTO images (userid, namebase, extension) VALUES ('%s', '%s', '%s');"
            % (current_user.userid, namebase, extension))
    except Exception:
        db.rollback()
        cur.close()
        # internal server error
        return jsonify("Database error: cannot insert into `images`"), 500

    # compose all names
    imname_base = namebase + '.' + extension
    tnname_base = namebase + '_tn.gif'
    cvname_base = namebase + '_cv.' + extension
    imname = webapp.config["SAVE_FOLDER"] + '/' + imname_base
    tnname = webapp.config["SAVE_FOLDER"] + '/' + tnname_base
    cvname = webapp.config["SAVE_FOLDER"] + '/' + cvname_base

    # save the original image
    file.save(imname)
    # save the thumbnail
    cmd_convert = "convert %s -auto-orient -thumbnail '200x200>' -gravity center -extent 200x200 -unsharp 0x.5 %s" % (
        imname, tnname)
    result_convert = os.system(cmd_convert)
    if (result_convert != 0
        ):  # if successfully converted, result_convert should have vlaue 0
        db.rollback()
        cur.close()
        os.remove(imname)
        return jsonify("Error: cannot create a thumnail"), 500
    # save the image with text detected using opencv
    success = detect_text(webapp.config["TOP_FOLDER"], imname, cvname)
    if not success:
        db.rollback()
        cur.close()
        os.remove(imname)
        os.remove(tnname)
        return jsonify("Text detection failed, please re-upload."), 500

    # upload to s3
    try:
        s3_client.upload_file(imname, webapp.config["S3_BUCKET_NAME"],
                              imname_base)
        s3_client.upload_file(tnname, webapp.config["S3_BUCKET_NAME"],
                              tnname_base)
        s3_client.upload_file(cvname, webapp.config["S3_BUCKET_NAME"],
                              cvname_base)
    except Exception:
        db.rollback()
        cur.close()
        os.remove(imname)
        os.remove(cvname)
        os.remove(tnname)
        return jsonify("Cannot upload image"), 500

    db.commit()
    cur.close()
    # remove temp files
    os.remove(imname)
    os.remove(cvname)
    os.remove(tnname)
    # flash the message to let users know that image uploading is successful
    flash("The new photo is successfully uploaded!")
    # display the original image and the version with text deteced side by side
    return jsonify("Successfully uploaded"), 200
Exemple #29
0
def save_house():
    """
    房东发布房源信息
    前端发送过来的json数据
    {
        "title":"",
        "price":"",
        "area_id":"1",
        "address":"",
        "room_count":"",
        "acreage":"",
        "unit":"",
        "capacity":"",
        "beds":"",
        "deposit":"",
        "min_days":"",
        "max_days":"",
        "facility":["7","8"]
    }
    """
    user_id = g.user_id
    data = request.get_data()
    #data = request.get_json()   # 直接获取json数据
    if not data:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    house_info = json.loads(data)
    #house_info = data

    user_id = user_id,
    title = house_info.get("title")
    price = house_info.get("price")
    address = house_info.get("address")
    room_count = house_info.get("room_count")
    acreage = house_info.get("acreage")
    unit = house_info.get("unit")
    capacity = house_info.get("capacity")
    beds = house_info.get("beds")
    deposit = house_info.get("deposit")
    min_days = house_info.get("min_days")
    max_days = house_info.get("max_days")
    area_id = house_info.get("area_id")

    # 校验传入数据
    if not all((title, price, area_id, address, room_count, acreage, unit,
                capacity, beds, deposit, min_days, max_days)):
        return jsonify(errno=RET.PARAMERR, errmsg="参数缺失")

    # 前端传过来的单价和押金是以元为单位,转换为分
    try:
        price = int(float(price) * 100)
        deposit = int(float(deposit) * 100)
    except Exception as e:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 保存房屋基本信息数据到数据库
    house = HouseInfo(user_id=user_id,
                      title=title,
                      price=price,
                      address=address,
                      room_count=room_count,
                      acreage=acreage,
                      unit=unit,
                      beds=beds,
                      deposit=deposit,
                      min_days=min_days,
                      max_days=max_days,
                      area_id=area_id)
    db.session.add(house)
    if house_info.get("facility"):
        # 查询设施id在house_info["facilities"]列表里面  select * from xxx where id in house_info["facilities"]
        try:
            facilities = Facility.query.filter(
                Facility.id.in_(house_info["facility"])).all()
            house.facilities = facilities
        except Exception as e:
            logging.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库错误')
    # 保存数据库
    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据错误')
    return jsonify(errno=RET.OK, errmsg="ok", data={"house_id": house.id})
Exemple #30
0
def internal_error(error):
	db.rollback()
	return render_template('500.html'),500
Exemple #31
0
def upload():
    '''
    Specify what happens when the login link is accessed.
    Only logged in users can access this link; others will be redirected to the login page.

    The images table in the database have the following columns:
        imid, userid, namebase, extension

    For an uploaded file, only its filename, seprated into namebase and extension, will be saved into the database.
    The image file itself is stored into the local file system, together with its thumbnail and opencv processed version with text detection. 

    Duplicate filenames are okay since each will have the userid and count added to the path they are saved locally. 
    The actual path an image is saved will be: 
        webapp.config["SAVE_FOLDER"]/namebase_userid_count.extension
    Its thumbnail path will be:
        webapp.config["SAVE_FOLDER"]/namebase_userid_count_tn.extension
    Its opencv-processed version path will be:
        webapp.config["SAVE_FOLDER"]/namebase_userid_count_cv.extension
    '''

    utils.record_requests()
    if request.method == 'POST':
        # get info about the user-uploaded image
        try:
            file = request.files['image']
        # Do not allow images bigger than 10M
        except RequestEntityTooLarge:
            return render_template('error.html',
                                   error="Image exceeds size limit (10M).")
        # Do not allow empty upload
        if file.filename == '':
            return render_template('error.html', error="No image selected.")
        # Get a secure version of the filenmae
        filename = secure_filename(file.filename)
        print(filename)
        # Separate filename and extension for easier name composition for original, thumbnail and opencv processed version
        filename, extension = filename.rsplit('.', 1)
        # Only allow JPG and PNG images
        if extension not in ['jpg', 'jpeg', 'png']:
            return render_template('error.html',
                                   e="Only JPG and PNG images are allowed!")

        # access database
        cur = db.cursor()
        # read count from table users for naming the uploaded image
        try:
            cur.execute("SELECT count FROM users WHERE userid = '%d';" %
                        (current_user.userid))
        except Exception:
            cur.close()
            return render_template('error.html')
        count = cur.fetchone()
        if (count == None):
            return render_template('error.html')
        count = count[0]

        # compose the namebase
        namebase = '_'.join([filename, str(current_user.userid), str(count)])

        # if successfully uploadded, update count in users table
        try:
            cur.execute("UPDATE users SET count = '%d' WHERE userid = '%d';" %
                        (count + 1, current_user.userid))
        except Exception:
            db.rollback()
            cur.close()
            return render_template('error.html')

        # insert new entry (i.e. new image) into the users table
        try:
            cur.execute(
                "INSERT INTO images (userid, namebase, extension) VALUES ('%s', '%s', '%s');"
                % (current_user.userid, namebase, extension))
        except Exception:
            db.rollback()
            cur.close()
            return render_template('error.html')

        # compose all names
        imname_base = namebase + '.' + extension
        tnname_base = namebase + '_tn.gif'
        cvname_base = namebase + '_cv.' + extension
        imname = webapp.config["SAVE_FOLDER"] + '/' + imname_base
        tnname = webapp.config["SAVE_FOLDER"] + '/' + tnname_base
        cvname = webapp.config["SAVE_FOLDER"] + '/' + cvname_base
        # save the original image
        file.save(imname)

        # save the thumbnail
        cmd_convert = "convert %s -auto-orient -thumbnail '200x200>' -gravity center -extent 200x200 -unsharp 0x.5 %s" % (
            imname, tnname)
        result_convert = os.system(cmd_convert)
        if (result_convert != 0
            ):  # if successfully converted, result_convert should have vlaue 0
            db.rollback()
            cur.close()
            os.remove(imname)
            return render_template(
                'error.html',
                error="Thumbnail creation failed, please re-upload.")

        # save the image with text detected using opencv
        success = detect_text(webapp.config["TOP_FOLDER"], imname, cvname)
        if not success:
            db.rollback()
            cur.close()
            os.remove(imname)
            os.remove(tnname)
            return render_template(
                'error.html', error="Text detection failed, please re-upload.")

        # upload to s3
        try:
            s3_client.upload_file(imname, webapp.config["S3_BUCKET_NAME"],
                                  imname_base)
            s3_client.upload_file(tnname, webapp.config["S3_BUCKET_NAME"],
                                  tnname_base)
            s3_client.upload_file(cvname, webapp.config["S3_BUCKET_NAME"],
                                  cvname_base)
        except Exception:
            db.rollback()
            cur.close()
            os.remove(imname)
            os.remove(cvname)
            os.remove(tnname)
            return render_template('error.html', error="Cannot upload image")

        db.commit()
        cur.close()

        # remove temp files
        os.remove(imname)
        os.remove(cvname)
        os.remove(tnname)

        # flash the message to let users know that image uploading is successful
        flash("The new photo is successfully uploaded!")
        # display the original image and the version with text deteced side by side
        return display(imname=imname_base, cvname=cvname_base)
    return render_template('upload.html')
def close_test_db_connection(self):
    db.rollback()