def post(self): data = _account_parser.parse_args() if AccountModel.find_by_username(data['username']): return {"message": "A user with that username already exists"}, 400 account = AccountModel(**data) account.add_to_db() return {"message": "Account created successfully."}, 201
def post(self): data = AccountPost.parser.parse_args() account = AccountModel(**data) try: account.save_to_db() except Exception as e: return {"message": "An error occurred creating the account."}, 500 return account.json(), 201
def post(self, user_id): account_json = resource.get_json() data = account_schema.load(account_json) account = AccountModel(user_id, **data) try: account.save_to_db() except: return {"message": "An error occurred while adding the account."}, 500 return account_schema.dump(account), 201
def post(self): data = request.get_json() name = data.get("name") pwd = data.get("pwd") id_num = data.get("id_num") if not UserModel.query.filter(UserModel.name == name).first(): while True: # in real world this will surely be replaced with a better efficient/scalable service to generate # unique account number acc_num = random.randint(1000000001, 9999999999) if not AccountModel.query.filter( AccountModel.acc_num == acc_num).first(): break user = UserModel(name=name, password=pwd, id_num=id_num) db.session.add(user) db.session.commit() account = AccountModel(acc_num=acc_num, status=INACTIVE, balance=0, user_id=user.id) db.session.add(account) db.session.commit() return { "message": "User created", "account_number": account.acc_num, "account_status": account.status }, 201 else: return {"message": "username already registered"}, 409
def get(self, _id): account = AccountModel.find_by_id(_id) if account and account.user_id == get_jwt_identity(): return account_schema.dump(account) return {'message': 'Account not found'}
def get(self): params = _ARGUMENTS.parse_args() account_id = params.get('account_id') credit_debit = params.get('credit_debit') user = AccountModel.find(account_id) credits = [] debits = [] if user is None: return errors._USER_NOT_FOUND, server_code.NOT_FOUND if credit_debit is None: credits = CreditModel.find_all_credits(account_id) debits = DebitModel.find_all_credits(account_id) elif credit_debit == 0: credits = CreditModel.find_all_credits(account_id) elif credit_debit == 1: debits = DebitModel.find_all_credits(account_id) result = user.json() result["debits"] = [debit.json() for debit in debits] result["credits"] = [credit.json() for credit in credits] result["amount_credits"] = amount_credits = self.__sum(credits) result["amount_debits"] = amount_debits = self.__sum(debits) result[ "amount"] = user.initial_balance + amount_credits - amount_debits return result, server_code.OK
def delete(self, _id): account = AccountModel.find_by_id(_id) if account and account.user_id == get_jwt_identity(): account.delete_from_db() return {'message': f'Account with id:{_id} deleted'} return {'message': 'Account not found'}
def __validate_value(self, arguments_data): if arguments_data is None: return errors._NOT_FOUND, server_code.INTERNAL_SERVER_ERROR if AccountModel.find(arguments_data.get('account_id')) is None: return errors._USER_NOT_FOUND, server_code.BAD_REQUEST if arguments_data.get("value") <= 0: return errors._VALUE_ERROR, server_code.BAD_REQUEST return None, None
def delete(self, name): account = AccountModel.find_by_name(name) if account: mall = MallModel.find_by_id(account.id) if mall: mall.delete_from_db() account.delete_from_db() return {'message': "Account with name '{}' deleted".format(name)} return {'message': 'Account not found.'}, 404
def signup_post(): email = request.form.get("email") firstname = request.form.get("firstname") lastname = request.form.get("lastname") password = request.form.get("password") user = AccountModel.query.filter_by(email=email).first() if user: flash(gettext("user_email_exists")) return redirect(url_for("auth.signup")) new_user = AccountModel(email=email, firstname=firstname, lastname=lastname, password=AccountModel.encrypt_password(password)) new_user.save_to_db() return redirect(url_for("auth.login"))
def post(cls): # get data from parser data = _account_parser.parse_args() # find user in database account = AccountModel.find_by_username(data['username']) # check password if account and safe_str_cmp(account.password, data['password']): access_token = create_access_token(identity=account.id, fresh=True) return {'access_token': access_token}, 200 return {'message': 'Invalid credentials'}, 401
def post(self): parser = reqparse.RequestParser() parser.add_argument( 'email', type=str, required=True, help="This field cannot be left blank!" ) parser.add_argument( 'password', type=str, required=True, help="This field cannot be left blank!" ) data = parser.parse_args() # admin case usernameAdmin = current_app.config['ADMIN']['username'] passwordAdmin = current_app.config['ADMIN']['password'] if data['email'] == usernameAdmin: if data['password'] == passwordAdmin: user = AccountModel('Admin', usernameAdmin, passwordAdmin, 'admin') access_token = create_access_token(identity=user) return { 'message': 'Logged in as admin', 'role': user.role, 'access_token': access_token, } else: user = AccountModel.find_by_email(data['email']) if not user: return {'message': 'User {} doesn\'t exist'.format(data['email'])} if user.check_password(data['password']): access_token = create_access_token(identity=user) return { 'message': 'Logged in as {} ({})'.format(user.role, user.email), 'role': user.role, 'access_token': access_token, } return {'message': 'Wrong credentials'}
def put(self, _id): account_json = resource.get_json() data = account_schema.load(account_json) account = AccountModel.find_by_id(_id) if account: for key in data: setattr(account, key, data[key]) account.save_to_db() return account_schema.dump(account), 200 return {'message': 'Account not found'}
def put(self, name): data = Account.parser.parse_args() account = AccountModel.find_by_name(name) if account is None: account = AccountModel(name, **data) else: account.is_active = data['is_active'] account.save_to_db() return account.json()
def post(self): parser = reqparse.RequestParser() parser.add_argument( 'name', type=str, required=True, help="This field cannot be left blank!" ) parser.add_argument( 'email', type=str, required=True, help="This field cannot be left blank!" ) parser.add_argument( 'password', type=str, required=True, help="This field cannot be left blank!" ) data = parser.parse_args() try: new_user = AccountModel( name=data['name'], email=data['email'], password=data['password'], role=self.role ) new_user.save_to_db() access_token = create_access_token(identity=new_user) return { 'message': 'User {} was created'.format(data['email']), 'role': self.role, 'access_token': access_token, } except AssertionError as exception_message: return {'message': 'Error: {}.'.format(exception_message)}, 400
def post(self): data = Account.parser.parse_args() user_id = data['user_id'] balance = data['balance'] user = AccountModel.find_by_user_id(user_id) if user: AccountModel.update_account(user_id, balance) return {"message": "Account Update Successful"}, 201 user_account = AccountModel(user_id, balance) user_account.save_user_account() return {"message": "Account Creation Successful"}, 201
class AccountController: model = AccountModel() # @classmethod # def choose(cls, parent=None): # from views.application_wizard import ApplicationWizard # dlg = ApplicationWizard(parent) # result = dlg.exec() # item = dlg.getResult() # return result, item @classmethod def create(cls, application, parent=None): from views.account_form import AccountForm dlg = AccountForm(parent) dlg.setApplication(application) result = dlg.exec() if result == AccountForm.Accepted: account = dlg.getAccount() while not cls.model.saveItem(account): p = QMessageBox().warning(parent, 'Ошибка', 'Потеряно соединение с сервером. Повторить?\nПри отмене программа будет ' 'закрыта, а несохраненные изменения потеряны.', QMessageBox.Retry | QMessageBox.Cancel) if p != QMessageBox.Retry: die() application.account = account return True return False @classmethod def edit(cls, account, parent=None): from views.account_form import AccountForm dlg = AccountForm(parent) dlg.setAccount(account) result = dlg.exec() if result == AccountForm.Accepted: account = dlg.getAccount() while not cls.model.saveItem(account): p = QMessageBox().warning(parent, 'Ошибка', 'Потеряно соединение с сервером. Повторить?\nПри отмене программа будет ' 'закрыта, а несохраненные изменения потеряны.', QMessageBox.Retry | QMessageBox.Cancel) if p != QMessageBox.Retry: die() return True return False
def post(self, name): if AccountModel.find_by_name(name): return { "message": "An item with name '{}' already exists." .format(name)}, 400 data = Account.parser.parse_args() account = AccountModel(name, **data) try: account.save_to_db() except: return {"message": "An error occurred adding the account."}, 500 return account.json(), 201
def getPosts(self): accounts = AccountModel.find_all() urls = [(self.url + account.name) for account in accounts] i = 0 for url in urls: print('Pulling posts from {}...'.format(url)) rss = 'https://api.rss2json.com/v1/api.json?rss_url={}'.format( urllib.parse.quote_plus(url)) data = requests.get(rss).json() print('====== ' + data['status'] + ' ======') for item in data['items']: pub_date = datetime.strptime(item['pubDate'], '%Y-%m-%d %H:%M:%S') # if exists, do not save unless pubDate is different post = PostModel.find_by_title(item['title']) categories = [ CategoryModel.get_or_create(category) for category in item['categories'] ] description = getBlurb(item['description']) new_post = PostModel(accounts[i].id, item['title'], pub_date, item['link'], item['author'], item['thumbnail'], description, item['content'], categories) if post is None: # add new new_post.save_to_db() else: if pub_date != post.pub_date: # delete old post.delete_from_db() new_post.save_to_db() i += 1
def list(account, page_num, page_size): page = AccountModel.list(account, page_num, page_size) return Response(data=page)
def delete(cls, user_id): account = AccountModel.find_by_id(user_id) if not account: return {'message': 'Account not found'}, 404 account.delete_from_db() return {'message': 'Account deleted'}, 200
def get(cls, user_id): account = AccountModel.find_by_id(user_id) if not account: return {'message': 'Account not found'}, 404 return account.json()
def get(self): """Retrieve all Accounts using pagination.""" from app import pagination return {'accounts': pagination.paginate(AccountModel, AccountModel.account_filed())}
""" Flask_RESTful resources for account creation """ from flask_restful import Resource, reqparse from flask import Request from models.account import AccountModel import re _model = AccountModel() class AccountResource(Resource): def __init__(self): super().__init__() self.model = _model # TODO: Authentication on this endpoint(!) def get(self, account_id): account = self.model.find_by_id(account_id) if not account: return {"message": "Account not found"}, 404 return account.dict def delete(self, account_id): success, account = self.model.delete_by_id(account_id) if not account: return {"message": "Account not found"}, 404 if success: return {"message": "Successfully deleted account"}
def get(self): accounts = [account.json() for account in AccountModel.find_all()] return { 'accounts': accounts }
def delete(self, name): account = AccountModel.find_by_name(name) if account is None: return {'message': "No account exists."} account.delete_from_db() return {'message': "Account deleted"}
def get(self, name): account = AccountModel.find_by_name(name) if account: return account.json() else: return {'message': 'Account not found'}, 404
def update(account): if not account: abort(400, **get_result(code=400, msg='参数错误')) AccountModel.update(account) return Response(data={})