def get(self, id): instance = self.__model_class__.query.get(id) if instance is None: return jsonify( {"message": self.__model_class__.__name__ + " not found"}), 404 return jsonify(instance, expand=self.__always_expand__)
def wrapped_fn(*args, **kwargs): token = request.headers.get('Authorization') if token is None: return jsonify({"message": "Authorization required"}), 403 user = User.verify_auth_token(token) if user: return fn(*args, **kwargs) else: return jsonify({"message": "Session token is invalid"}), 403
def delete(self, id): self.__model_class__.query.filter_by(id=id).delete() try: db.session.commit() return jsonify({"id": id}), 200 except sqlalchemy.exc.SQLAlchemyError, exc: reason = exc.message db.session.rollback() return jsonify({"message": reason}), 400
def put(self, id): instance = self.__model_class__.query.get(id) instance.deserialize(request.json) try: db.session.commit() return jsonify(instance, expand=self.__always_expand__) except sqlalchemy.exc.SQLAlchemyError, exc: reason = exc.message db.session.rollback() return jsonify({"message": reason}), 400
def post(self): instance = self.__model_class__.from_json(request.json) db.session.add(instance) try: db.session.commit() db.session.refresh(instance) return jsonify(instance, expand=self.__always_expand__), 201 except sqlalchemy.exc.SQLAlchemyError, exc: reason = exc.message db.session.rollback() return jsonify({"message": reason}), 400
def register(): user = User.from_json(request.json) if 'password' not in request.json: return jsonify({"message": "Password is required"}) password = request.json['password'] user.hash_password(password) db.session.add(user) try: db.session.commit() except sqlalchemy.exc.IntegrityError, exc: reason = exc.message db.session.rollback() return jsonify({"message": reason}), 400
async def delete_wordlists(request, data={}): try: if not data: data = ujson.loads(request.body) except: return json({}, status=400) wordlist_name = data.get("name").replace( "'", "''") if data.get("name") else "未命名" user_id = data.get("user_id") if data.get( "user_id") else request['session'].get('user_id') if user_id: async with request.app.db as cur: r = await cur.fetch( "select * from word_list where name='%s' and user_id=%s" % (wordlist_name, user_id)) if r: wordlist_id = r[0]['id'] await cur.fetch( "delete from user_words where word_list_id=%s" % wordlist_id) res = await cur.fetch( "delete from word_list where name='%s' and user_id=%s returning *" % (wordlist_name, user_id)) return json(jsonify(r)) return json({}, status=400)
async def add_wordlists_word(request, wordlist_id, data={}): user_id = None try: if not data: data = ujson.loads(request.body) except: return json({}, status=400) if request['session'].get('user_id'): user_id = request['session'].get('user_id') if user_id and data.get('word'): async with request.app.db as cur: records = await cur.fetch( "select * from word_list where id=%s and user_id=%s" % (wordlist_id, user_id)) if records: words = records[0]['words'] if data.get('word') not in words: words.append(data.get('word')) words = str(list(words)).replace('[', '{').replace( ']', '}').replace("'", '"') records = await cur.fetch( """update word_list set words='%s' where id=%s returning *""" % (words, wordlist_id)) r = await cur.fetch( """insert into user_words (create_time,word,words_level,user_id,review_time, word_list_id) values (current_timestamp,'%s',%s,%s,current_timestamp,%s) returning *""" % (data.get('word'), 0, user_id, wordlist_id)) print(r) if records: return json(jsonify(records)[0]) return json({})
def login(): username = request.json.get('username') password = request.json.get('password') user = User.verify_auth_token(username) if not user: # try to authenticate with username/password user = User.query.filter_by(username=username).first() if user: if user.verify_password(password): token = user.generate_auth_token() return jsonify( {"sessionToken": token.decode('ascii'), "duration": SESSION_TOKEN_DURATION, "currentUser": user}) else: return jsonify({"message": "password is incorrect"}), 401 else: return jsonify({"message": "Can not find this username"}), 401
def get_user(id): user = User.query.get(id) if not user: jsonify({"message": "User not found"}), 404 if request.method == 'GET': return jsonify(user) elif request.method == 'PUT': user.name = get_json_key(request.json, 'name') user.username = get_json_key(request.json, 'username') user.email = get_json_key(request.json, 'email') try: db.session.commit() return jsonify(user) except sqlalchemy.exc.IntegrityError, exc: reason = exc.message db.session.rollback() return jsonify({"message": reason}), 400
def new_user(): username = request.json.get('username') password = request.json.get('password') if username is None or password is None: abort(400) # missing arguments if User.query.filter_by(username=username).first() is not None: return jsonify({"message": "User already exist"}), 400 user = User(username=username) user.hash_password(password) db.session.add(user) try: db.session.commit() return jsonify({'username': user.username}), 201 except sqlalchemy.exc.IntegrityError, exc: reason = exc.message db.session.rollback() return jsonify({"message": reason}), 400
async def get_wordlists(request): wordlist_id = request.args.get('id', 0) user_id = None if request['session'].get('user_id'): user_id = request['session'].get('user_id') if user_id and wordlist_id == 0: async with request.app.db.acquire() as cur: records = await cur.fetch( "select * from word_list where user_id=%s" % (user_id)) return json(jsonify(records)) elif user_id: async with request.app.db.acquire() as cur: records = await cur.fetch( "select * from word_list where user_id=%s and id =%s" % (user_id, wordlist_id)) return json(jsonify(records)) return json({}, status=400)
async def delete_wordlist(request, wordlist_id): user_id = request['session'].get('user_id') if user_id: async with request.app.db as cur: records = await cur.fetch( "delete from word_list where user_id=%s and id=%s returning *" % (user_id, wordlist_id)) if records: return json(jsonify(records)[0]) return json({}, status=400)
def login(): username = request.json.get('username') password = request.json.get('password') user = User.verify_auth_token(username) if not user: # try to authenticate with username/password user = User.query.filter_by(username=username).first() if user: if user.verify_password(password): token = user.generate_auth_token() return jsonify({ "sessionToken": token.decode('ascii'), "duration": SESSION_TOKEN_DURATION, "currentUser": user }) else: return jsonify({"message": "password is incorrect"}), 401 else: return jsonify({"message": "Can not find this username"}), 401
async def get_wordlists_word(request, wordlist_id): user_id = None if request['session'].get('user_id'): user_id = request['session'].get('user_id') if user_id: async with request.app.db.acquire() as cur: records = await cur.fetch( "select * from word_list where id=%s and user_id=%s" % (wordlist_id, user_id)) if records: return json(jsonify(records)[0]["words"]) return json({}, status=400)
async def get_word_level(request, word_list_id): user_id = request['session'].get('user_id') words = [] current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') async with request.app.db.acquire() as cur: records = await cur.fetch( """select word from user_words where word_list_id=%s and review_time< '%s'""" % (word_list_id, current_time)) for record in jsonify(records): words.append(record['word']) return json(words) return json([])
async def add_user(request, fromu=None): data = {} try: if not fromu: data = ujson.loads(request.body) else: data = {"username": fromu} except: return json({}, status=400) if data.get('username') and len(data.get('username')) > 5: async with request.app.db.acquire() as cur: records = await cur.fetch( "select * from users where username='******'" % data.get('username')) if records: request['session']['user_id'] = records[0]['id'] return json(jsonify(records)[0]) else: sql = """insert into users (create_time,username,name,wechat_user) values (current_timestamp,'%s','%s','%s') returning *""" user_info = (data.get('username'), data.get('name') if data.get('name') else data.get('username'), data.get('wechat_user') if data.get('wechat_user') else 'NULL') records = await cur.fetch(sql % user_info) print(records) if records: request['session']['user_id'] = records[0]['id'] res = await add_wordlist(request, data={"name": "新手起步"}) if res: wordlist_id = ujson.loads(res.body)['id'] r = await add_wordlists_word(request, wordlist_id, data={"word": "hello"}) return (r.body) if records: return json(jsonify(records)[0]) return json({}, status=400)
async def add_wordlist(request, data={}): try: if not data: data = ujson.loads(request.body) except: return json({}, status=400) wordlist_name = data.get("name").replace( "'", "''") if data.get("name") else "未命名" user_id = data.get("user_id") if data.get( "user_id") else request['session'].get('user_id') if user_id: async with request.app.db as cur: r = await cur.fetch( "select * from word_list where name='%s' and user_id=%s" % (wordlist_name, user_id)) if r: return json(jsonify(r)[0]) else: records = await cur.fetch( "insert into word_list (create_time,words,name,category,user_id) VALUES (current_timestamp,'{}','%s','private',%s) returning *" % (wordlist_name, user_id)) if records: return json(jsonify(records)[0]) return json({}, status=400)
async def update_word_level(request, word_list_id, words=None): user_id = request['session'].get('user_id') result = [] if not words: words = ujson.loads(request.body) for word in words: word_text = word['word'] async with request.app.db.acquire() as cur: record = await cur.fetch( """select words_level from user_words where word='%s' and user_id=%s and word_list_id=%s""" % (word_text, user_id, word_list_id)) level = record[0]["words_level"] state = word['state'] if state == 'remember': level = level + 1 if level <= 11 else level review_time = datetime.datetime.now() + review_time_list[str( level)] async with request.app.db.acquire() as cur: r = await cur.fetch( """update user_words set words_level = %s,review_time= '%s' where user_id=%s and word='%s' returning *""" % (level, review_time.strftime('%Y-%m-%d %H:%M:%S'), user_id, word_text)) elif state == 'confuse': review_time = datetime.datetime.now() async with request.app.db.acquire() as cur: r = await cur.fetch( """update user_words set words_level = %s,review_time= '%s' where user_id=%s and word='%s' returning *""" % (level, review_time.strftime('%Y-%m-%d %H:%M:%S'), user_id, word_text)) elif state == 'not remember': level = 0 async with request.app.db.acquire() as cur: r = await cur.fetch( """update user_words set words_level = %s where user_id=%s and word='%s' returning *""" % (level, user_id, word_text)) result.append(jsonify(r)) return json(result)
def get_all(self): return jsonify(self.__model_class__.query.all())
user = User.verify_auth_token(username) if not user: # try to authenticate with username/password user = User.query.filter_by(username=username).first() if user: if user.verify_password(password): token = user.generate_auth_token() return jsonify( {"sessionToken": token.decode('ascii'), "duration": SESSION_TOKEN_DURATION, "currentUser": user}) else: return jsonify({"message": "password is incorrect"}), 401 else: return jsonify({"message": "Can not find this username"}), 401 @auth.route('/api/register', methods=['POST']) def register(): user = User.from_json(request.json) if 'password' not in request.json: return jsonify({"message": "Password is required"}) password = request.json['password'] user.hash_password(password) db.session.add(user) try: db.session.commit() except sqlalchemy.exc.IntegrityError, exc: reason = exc.message db.session.rollback() return jsonify({"message": reason}), 400 return jsonify(user), 201
def get(self, id): instance = self.__model_class__.query.get(id) if instance is None: return jsonify({"message": self.__model_class__.__name__ + " not found"}), 404 return jsonify(instance, expand=self.__always_expand__)
def user_list(): return jsonify(User.query.all())
user = User.query.filter_by(username=username).first() if user: if user.verify_password(password): token = user.generate_auth_token() return jsonify({ "sessionToken": token.decode('ascii'), "duration": SESSION_TOKEN_DURATION, "currentUser": user }) else: return jsonify({"message": "password is incorrect"}), 401 else: return jsonify({"message": "Can not find this username"}), 401 @auth.route('/api/register', methods=['POST']) def register(): user = User.from_json(request.json) if 'password' not in request.json: return jsonify({"message": "Password is required"}) password = request.json['password'] user.hash_password(password) db.session.add(user) try: db.session.commit() except sqlalchemy.exc.IntegrityError, exc: reason = exc.message db.session.rollback() return jsonify({"message": reason}), 400 return jsonify(user), 201