def create_test_data(file): conn = sqlite3.connect(file) conn.row_factory = sqlite3.Row cursor = conn.cursor() users = [ User("pabloi09", "password").to_insert(), User("prueba", "password").to_insert(), User("prueba2", "password").to_insert(), ] with open(PROJECT_PATH.format( "reddit_downloader/config.json")) as json_config: reddit_config = json.load(json_config) with open(PROJECT_PATH.format("twitter_util/config.json")) as json_config: twitter_config = json.load(json_config) with open( PROJECT_PATH.format("instagram_util/config.json")) as json_config: insta_config = json.load(json_config) projects = [ Project(reddit_config, twitter_config, insta_config, 1).to_insert(), #Project(reddit_config, twitter_config, insta_config,1).to_insert(), #Project(reddit_config, twitter_config, insta_config,2).to_insert(), #Project(reddit_config, twitter_config, insta_config,3).to_insert(), #Project(reddit_config, twitter_config, insta_config,3).to_insert(), ] cursor.executemany( "INSERT INTO project(reddit_config, twitter_config, insta_config, user_id) VALUES (?,?,?,?)", projects) conn.commit() cursor.execute("select * from project") projects = cursor.fetchall() for project in projects: p = Project.from_database(project) p.reddit_config["path"] = REDDIT_PATH.format(p.user_id, p.project_id) p.insta_config["cookie_location"] = INSTA_PATH.format( p.user_id, p.project_id) q = p.to_insert() cursor.execute( "UPDATE project SET reddit_config = ?, insta_config = ? WHERE project_id = ?", (q[0], q[2], p.project_id)) cursor.executemany( "INSERT INTO tw_engagement(username, project_id) VALUES (?,?)", [(username, p.project_id) for username in twitter_config["engagement_accounts"]]) cursor.executemany( "INSERT INTO insta_engagement(username, project_id) VALUES (?,?)", [(username, p.project_id) for username in insta_config["engagement_accounts"]]) conn.commit() conn.close()
def save(self, _dict): user = User(**_dict) database.session.add(user) database.session.commit() return user
def sign_up(): body = request.get_json() user = User(**body) user.hash_password() user.save() id = user.id return {'id': str(id)}, 200
def post(): """[Signup] Raises: SchemaValidationError: [Error in data] EmailAlreadyExistsError: [Email exists] InternalServerError: [Query error] Returns: [json] -- [Json object with message and status code] """ try: body = request.get_json() user = User(**body) user.hash_password() user.save() userId = user.id return tokenCreation(user, body, "Successfully signed up", userId) except FieldDoesNotExist as e: print(e) raise SchemaValidationError except NotUniqueError as e: print(e) for field in User._fields: # You could also loop in User._fields to make something generic if field in str(e): if field == 'username': raise UserNameDoesnotExistsError if field == 'email': raise EmailAlreadyExistsError except Exception as e: print(e) raise InternalServerError
def register(): body = request.get_json() try: # userRegistrationSchema.validate(body) username = body.get('username') user_email = body.get('email') firstname = body.get('firstname') lastname = body.get('lastname') gender = body.get('gender') password = body.get('password') user_password = bcrypt.generate_password_hash( password=password).decode('utf-8') users_registered = User.objects(username=username) if len(users_registered) == 0: User(username=username, email=user_email, password=user_password, gender=gender, firstname=firstname, lastname=lastname).save() new_profile = User.objects(username=username)[0] return { 'username': new_profile.username, 'email': new_profile.email, 'token': get_token() }, 201 else: return jsonify({'message': 'User already exists!'}), 409 except Exception as e: return {'error': str(e)}, 400
def create_user(): try: body = request.get_json() body['password'] = bcrypt.generate_password_hash(body['password']) User(**body).save() return make_response({"completed": "true"}, 200) except: return make_response({"error": "Bad Request"}, 400)
def register(): if request.method == 'POST': try: User(username=request.form['username'], password=request.form['password']).save() return redirect(url_for('login')) except: return render_template('index.html', message="User Already Exists") else: return render_template('register.html')
def create_user(): user_schema = user.UserSchema(strict=True, many=False) user_data = request.get_json() data = user_schema.load(user_data).data print(data) new_user = User(name=data["name"]) session.add(new_user) session.commit() result = user_schema.dump(new_user) return jsonify(result[0])
def post(self): try: body = request.get_json() password_hash = generate_password_hash(body.get('password')) body['password'] = password_hash user = User(**body).save() id = user.id return {'msg': 'user is created successfully', 'id': str(id)}, 200 except (FieldDoesNotExist, ValidationError): raise SchemaValidationError except NotUniqueError: raise UserAlreadyExistsError except Exception as err: raise InternalServerError
def create_user(data): try: user = User(name=data['name'], email=data['email'], password=data['password']) db.session.add(user) db.session.commit() return make_response( jsonify({ 'message': 'data added to database', 'user_id': user.id }), 200) except Exception as e: return make_response(jsonify({'message': e.__doc__}), 500)
def post(self): # Creates a User in the db. Do not pass in a user_id, the DB created this! parser = reqparse.RequestParser() parser.add_argument('first_name', type=str, required=True) parser.add_argument('last_name', type=str, required=True) parser.add_argument('email', type=email, required=True) parser.add_argument('phone', type=str, required=True) parser.add_argument('paypal_id', type=str, required=True) parser.add_argument('password', type=str, required=True) parser.add_argument('saved_address', type=str, required=True) args = parser.parse_args(strict=True) new_user = self.update_sqlachemy_object(User(), args) db.session.add(new_user) db.session.commit() return self.make_response_from_sqlalchemy( new_user), 201 # HTTP 201 CREATED
def new_user(user_data: User_Create, db: Session = Depends(get_db)): ''' Add new user to the System Args: User_Create schema data format provide details to add new user Response: 200 - data of the new user is returned. Data in User_Create schema format 400 - when user email ID already exists. Response in json data ''' try: user = User(**user_data.dict()) db.add(user) db.commit() return user except: raise HTTPException(status_code=400, detail="User already exists")
def post(self): body = request.get_json() user = User(**body).save() id = user.id return {'id': str(id)}, 200
def seed_users(): return [ User(name="seed_user_1"), User(name="seed_user_2"), ]