def usersDetail(id): if request.method == "GET": return UserController.show(id) elif request.method == "PUT": return UserController.update(id) elif request.method == "DELETE": return UserController.delete(id)
def delete(model_id): """ Delete an existing User --- parameters: - name: model_id in: path type: string description: The ID of the user required: true definitions: User: type: object properties: id: type: integer email: type: string responses: 200: description: Display a single user schema: type: string example: { "message": "User has been deleted"} 404: description: User could not be found schema: type: string example: { "message": "User could not be found"} """ return UserController.delete(model_id)
def register(): stripe.api_key = current_app.config["STRIPE_API_KEY"] user = UserController.createFromRegistration(request.get_json()) baseUrl = request.headers.get("referer", "https://localhost:5000/") try: checkout_session = stripe.checkout.Session.create( success_url=baseUrl + "success?session_id={CHECKOUT_SESSION_ID}", cancel_url=baseUrl + "failed", payment_method_types=["card"], mode="subscription", line_items=[{ "price": stripe.Price.list()["data"][0]["id"], # For metered billing, do not pass quantity "quantity": 1, }], customer_email=user.email, client_reference_id=user.id, subscription_data={"trial_period_days": 30}, ) return jsonify({ "token": user.encodeToken().decode("utf-8"), "sessionId": checkout_session["id"], "pk": "pk_test_51I0Hi7AJqS6KUAStIg73brufDB8SmNTBqFvYFLyt7vAV1Ecbf7fPzDDIiwFflpnyD9tbYvaObpEpLhj9lBqROwZC00WywiUsQk", }) except Exception as e: print(e) return jsonify({"error": {"message": str(e)}}), 400
def get(model_id): """ Retrieve a single user by ID --- parameters: - name: model_id in: path type: string description: The ID of the user required: true definitions: User: type: object properties: id: type: integer email: type: string responses: 200: description: Display a single user schema: $ref: '#/definitions/User' 404: description: User could not be found schema: type: string example: { "message": "User could not be found"} """ return UserController.get(model_id)
def update_balance(userindex): data = get_data_from_ajax() balance = data.get("Balance", None) if balance is None: abort(400, u"缺少参数Balance") user = UserController.update_user_balance(userindex.UserID, balance) return return_data(None, data=user.dump_to_dict())
def userinfo(userindex): # data = get_data_from_ajax() # if data is None: # return # u = User.from_blockchain(userindex.UserID) u = UserController.get_user_byuserid(userindex.UserID) u.userindex = userindex if u is None: abort(403, u"用户不存在于区块链记录中或访问区块链失败") # u.UserInfo.CurrentCreditScore = u.CreditScore.CurrentCreditScore # u.UserInfo.TotalCreditScore = u.CreditScore.TotalCreditScore # u.UserInfo.RateCount = u.CreditScore.Ratetimes # u.UserInfo.save() d = UserController.wrapper_userinfo(u) # return return_data(None, data=u.dump_to_dict()) return return_data(None, data=d)
def finish_userdetail_info(userindex): data = get_data_from_ajax() userid = data.get("UserID", None) if userid is None: userid = data.get("IDNo", None) realname = data.get("RealName", None) gender = data.get("Gender", None) tele = data.get("Tele", None) userindex.IDNo = userid userindex.RealName = realname userindex.Gender = gender userindex.Tele = tele check_list = list() check_list.append(userid) check_list.append(realname) if userindex.Role == UserRole.Student: school = data.get("School") stuid = data.get("StuID") userindex.School = school userindex.StuID = stuid check_list.append(school) check_list.append(stuid) if check_list.count(None): abort(400, u"缺少完整参数: %d" % check_list.index(None)) userindex.School = school userindex.StuID = stuid elif userindex.Role == UserRole.Agency: agencyname = data.get("AgencyName") check_list.append(agencyname) if check_list.count(None): abort(400, u"缺少完整参数: %d" % check_list.index(None)) userindex.AgencyName = agencyname else: abort(400, "role error!") userindex.save() print(userindex.dump_to_dict()) # user = UserController.create_user(userindex) # return return_data(None, data=user.dump_to_dict()) u = UserController.get_user_byuserid(userindex.UserID) u.userindex = userindex d = UserController.wrapper_userinfo2(u) return return_data(None, data=d)
def test_BlackList(models): # general set up Jim, Kim = Users() for user in Users(): user_in_db = UserController.createFromRegistration(user) users_token = user_in_db.encodeToken() token = BlackListToken(users_token) token.addToDB()
def update(model_id): """ Update an existing User --- parameters: - name: model_id in: path description: The ID of the user required: true type: string - name: body in: body required: true schema: type: object properties: email: type: string password: type: string password_confirmation: type: string required: - email responses: 200: description: User has been updated schema: $ref: '#/definitions/User' 404: description: User could not be found schema: type: string example: { "message": "User could not be found"} 422: description: Form Validation Error schema: type: string example: { "message": "password and confirmation are not the same"} 400: description: Bad Request schema: type: string example: { "message": "Request data must be a JSON object"} """ try: input_data = request.get_json(force=True) except Exception as error: return jsonify({"error": "Request data must be a JSON object"}), 400 if not isinstance(input_data, dict): return jsonify({"error": "Request data must be a JSON object"}), 400 return UserController.update(model_id, input_data)
def test_Users(models): Jim, Kim = Users() # register Jim jimInDB = UserController.createFromRegistration(Jim) updatedJim = jimInDB.set(test=True) jim = UserController.getFromId(jimInDB.id) assert isinstance(jim, UserController) assert str(jim) == "Jim Bob" # check all the attributes assert jim.email == Jim["email"] assert jim.phone_number == Jim["phone_number"] assert jim.password != Jim["password"] assert jim.test == True # use the login method jimsAPICall = {"email": Jim["email"], "password": Jim["password"]} jim = UserController.fromLogin(jimsAPICall) token = jim.encodeToken() # give the token back to the frontend # do some stuff # frontend submits a request to an auth_required route _jim = UserController.getFromToken(token) assert jim.id == _jim.id # register Kim kimInDB = UserController.createFromRegistration(Kim) # use the getFromId method kim = UserController.getFromId(kimInDB.id) assert isinstance(kim, UserController) assert str(kim) == "Kim Sue"
def student_apply(userindex): data = get_data_from_ajax() JobID = data.get("JobID", None) if JobID is None: abort(400, u"缺少 JobID") if JobID in userindex.JobTxMap.keys(): tx = Tx.from_blockchain(unicode(userindex.JobTxMap[JobID])) if tx is not None: tx.save() print "tx from existed data!" return return_data(data=tx.dump_to_dict()) tx = TxController.create_tx(userindex.UserID, JobID) # tx.save() # add tx status re-get # new_tx = Tx.from_blockchain(unicode(tx.id)) # if new_tx is None: # abort(403, u"创建 %s 没有成功" % tx.id) # new_tx.save() job = JobController.get_job_by_jobid(jobid=JobID) if job is not None: job.TotalApplied += 1 job.Txs.append(tx) # 自动审核通过 if userindex.CurrentCreditScore > 8: tx.Status = u"已通过" print("当前信用分数:") print(userindex.CurrentCreditScore) job.TotalHired += 1 else: # 自动审核未通过 tx.Status = u"未通过" job.TotalWaitCheck += 1 job.save() tx.save() userindex.JobTxMap[JobID] = unicode(tx.id) # {jobid: txid} print "job dump to dict" print job.dump_to_dict() print "user job tx map" print userindex.JobTxMap userindex.save() u = UserController.get_user_byuserid(userindex.UserID) u.JobIDs.append(unicode(job.id)) # 注意这个 待会测一下 u.save() return return_data(data=tx.dump_to_dict())
def get_all_jobs_by_time(): jobs = JobController.get_all_jobs_by_time() ret = list() max_count = 20 max_count = max_count if max_count < len(jobs) else len(jobs) for i in range(max_count): job = jobs[i] print job.PublishTime userindex = UserController.get_userindex_byuserid(job.UserID) if userindex is not None: ret.append({"AgencyName": userindex.AgencyName, "Score": userindex.CurrentCreditScore, "JobInfo": job.dump_to_dict()}) return return_data(data=ret)
def user_agency(): data = get_data_from_ajax() jobid = data.get("JobID", None) if jobid is None: abort(400, "缺少 JobID") jobinfo = JobController.get_job_by_jobid(jobid) if jobinfo is None: abort(403, "查询的 JobID: %s 不存在" % jobid) userindex = UserController.get_userindex_byuserid(jobinfo.UserID) d = userindex.dump_to_dict() d["Score"] = userindex.CurrentCreditScore d["JobsCount"] = len(userindex.JobTxMap) return return_data(None, data=d)
def update_score(userindex): data = get_data_from_ajax() score = data.get("Score", None) if score is None: abort(400, u"缺少参数Score") try: score = int(score) except ValueError: score = -1 if not (0 <= score <= 10): abort(403, u"Score 必须在 0<score<=10 之间") user = UserController.update_user_current_score(userindex.UserID, score) return return_data(None, data=user.dump_to_dict())
def create(): """ Create a new user --- parameters: - name: body in: body required: true schema: type: object properties: email: type: string password: type: string password_confirmation: type: string required: - email - password - password_confirmation responses: 201: description: User has been created schema: $ref: '#/definitions/User' 422: description: Form Validation Error schema: type: string example: { "message": "A password is required"} 400: description: Bad Request schema: type: string example: { "message": "Request data must be a JSON object"} """ try: input_data = request.get_json(force=True) except Exception as error: return jsonify({"error": "Request data must be a JSON object"}), 400 if not isinstance(input_data, dict): return jsonify({"error": "Request data must be a JSON object"}), 400 return UserController.create(input_data)
def register(): data = get_data_from_ajax() username = data.get('username', None) password = data.get('password', None) role = data.get('role', None) if username is None or password is None or role is None: abort(400, u"必须填写username和password和role") username = unicode(username) userindex = UserController.get_userindex_byname(username) if userindex is not None: abort(403, u"该用户(%s)已经注册过" % username) password = hashutil.hash_md5(unicode(password)) try: role = int(role) if role is not None else UserRole.Student except ValueError, e: abort(403, u"Role 必须为整数")
def all(): """ Retrieving a list of users --- definitions: User: type: object properties: id: type: integer email: type: string responses: 200: description: Display a list of users schema: $ref: '#/definitions/User' """ return UserController.all()
def job_query(): data = get_data_from_ajax() jobid = data.get("JobID", None) if jobid is None: abort(400, "缺少 JobID") # job = JobInfo.from_blockchain(jobid) job = JobController.get_job_by_jobid(jobid) if job is None: abort(403, u"没有查找到对应JobID: %s 的兼职信息" % jobid) # print type(job.id) job.save() d = job.dump_to_dict() username = data.get("username", None) if username is None: username = data.get("Username", None) if username is not None: userindex = UserController.get_userindex_byname(username) if userindex is not None: if jobid in userindex.JobTxMap.keys(): d["IsApplied"] = True else: d["IsApplied"] = False state = data.get("State", None) if state is not None: try: state = int(state) if not (0 <= state <= 4): abort(400, "State 只能是 0,1,2,3,4") except ValueError, e: abort(400, "State 只能是数字") txs = d["Txs"] l = list() for t in txs: if t['State'] == state: l.append(t) d["Txs"] = l
def login(): if current_user.is_authenticated: return redirect(url_for('index')) return UserController.login()
def createUser(): return UserController.create()
from flask_restplus import Resource from flask import request, jsonify from functools import wraps import jwt from app import api, app from app.controllers import UserController, BudgetController, MiniBudgetController from app.models import User user_object = UserController() budget_object = BudgetController() mini_budget_object = MiniBudgetController() def token_required(f): @wraps(f) def decorated(*args, **kwargs): token = None if 'token' in request.headers: token = request.headers['token'] if not token: return jsonify({'message': 'Token is missing!'}) try: data = jwt.decode(token, app.config['SECRET_KEY']) current_user = User.query.filter_by( username=data['username']).first() except: return jsonify({'message': 'Token is invalid!'}) return f(current_user, *args, **kwargs) return decorated
def login(): user = UserController.fromLogin(request.get_json()) return user.encodeToken()
if check_list.count(None): abort(400, u"缺少参数%d" % check_list.index(None)) try: s = int(salary) if s <= 0 or s > 65535: abort(400, u"Salary 设置不合理") except ValueError, e: abort(400, u"Salary 必须是一个整数") job = JobController.create_jobinfo(userindex, title, jobtime, place, salary, day, demand) userindex.JobTxMap[unicode(job.id)] = "" userindex.save() u = UserController.get_user_byuserid(userindex.UserID) u.JobIDs.append(unicode(job.id)) # 注意这个 待会测一下 u.save() return return_data(data=job.dump_to_dict()) @app.route('/job/agency/jobs', methods=['GET', 'POST']) @allow_cross_domain @check_auth def get_agency_jobs(userindex): """ from cache :param userindex: :return: """
def route_wrapper(*args, **kwargs): token = get_token_auth_header() user = UserController.getFromToken(token) return func(user, *args, **kwargs)
if tx is None: abort(403, u"提供的tx: %s 不存在" % txid) # tx.bc_evaluate(userid, score) # return tx state # lookup # tx = Tx.from_blockchain(txid) userindex.TotalCreditScore += score userindex.RateCount += 1 userindex.CurrentCreditScore = int(userindex.TotalCreditScore / userindex.RateCount) userindex.save() # 只结算一次钱 if tx.Status != u"已结算": user = UserController.get_user_byuserid(userindex.UserID) job = JobController.get_job_by_jobid(tx.JobID) salary = int(job.JobDetail.Salary) if userindex.Role == 0: # user is student user.Balance += salary # get the agency agency = UserController.get_user_byuserid(job.UserID) agency.Balance -= salary else: # user is agency user.Balance -= salary # get the student st = UserController.get_user_byuserid(tx.UserID) st.Balance += salary tx.Status = u"已结算" tx.save() return return_data(data=tx.dump_to_dict())
def logout(): logout_user() return UserController.logout()
def route_wrapper(*args, **kwargs): token = get_token_auth_header() user = UserController.getFromToken(token) return func(RecipeController(user.id, user.active), *args, **kwargs)
def login(): return UserController.login()
def register(): if current_user.is_authenticated: return redirect(url_for('index')) return UserController.register()
def hash(): return UserController.hash()