def setUp(self): self._db_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'test.db') if os.path.exists(self._db_path): os.remove(self._db_path) self._db = PeerReviewDB('sqlite:///' + self._db_path, echo=False) # define test records self._test_users = [ User(id=0, login='******'), User(id=1, login='******'), User(id=2, login='******'), ] self._test_tasks = [ Task(name='task0'), Task(name='task1'), Task(name='task2'), ] self._test_user_tasks = [ UserTask(user=self._test_users[0], task=self._test_tasks[0], url='!', status=TaskStatus.WAITING_REVIEW, timestamp=0), UserTask(user=self._test_users[0], task=self._test_tasks[1], url='@', status=TaskStatus.COMPLETE, timestamp=1), UserTask(user=self._test_users[1], task=self._test_tasks[0], url='#', status=TaskStatus.IN_WORK, timestamp=0), UserTask(user=self._test_users[2], task=self._test_tasks[2], url='^', status=TaskStatus.COMPLETE, timestamp=0), ] self._test_reviews = [ Review(reviewer=self._test_users[0], reviewed_task=self._test_user_tasks[2], status=ReviewStatus.IN_WORK, issue_url='$'), Review(reviewer=self._test_users[1], reviewed_task=self._test_user_tasks[1], status=ReviewStatus.CLOSED, issue_url='%'), ]
def setup(): global user_data user01 = User( userID="1000", name="Roxie Joddens", email="*****@*****.**", phone="+358-119-977-5220", friends=[], ) user02 = User( userID="1001", name="Aundrea Izard", email="*****@*****.**", phone="+4084687956", friends=[], ) user03 = User( userID="1002", name="Teddy Bolan", email="*****@*****.**", phone="+4084689120", friends=[], ) user04 = User( userID="1003", name="Avril Joyson", email="*****@*****.**", phone="+4086884546", friends=[], ) user01.friends.append(user02) user01.friends.append(user04) user02.friends.append(user04) user02.friends.append(user03) user03.friends.append(user02) user_data.append(user01) user_data.append(user02) user_data.append(user03) user_data.append(user04)
def create_user(login_session): new_user = User(username=login_session['username'], email=login_session['email']) session.add(new_user) session.commit() user = session.query(User).filter_by(email=login_session['email']).first() return user.id
def test_hash_and_eq(self): user0 = self._test_users[0] identical_user = User(id=user0.id, login=user0.login) self.assertIsNot(user0, identical_user) self.assertEqual(user0, identical_user) self.assertEqual(hash(user0), hash(identical_user))
def test_insert1(env): users = [] user1 = User() user1.oid = 1 user1.name = 'Homer Simpson' user1.authid = 'homer' user1.email = '*****@*****.**' user1.birthday = datetime.date(1950, 12, 24) user1.is_friendly = True user1.tags = ['relaxed', 'beerfan'] users.append(user1) user2 = User() user2.oid = 2 user2.name = 'Crocodile Dundee' user2.authid = 'crocoboss' user2.email = '*****@*****.**' user2.birthday = datetime.date(1960, 2, 4) user2.is_friendly = False user2.tags = ['red', 'yellow'] user2.referred_by = user1.oid users.append(user2) user3 = User() user3.oid = 3 user3.name = 'Foobar Space' user3.authid = 'foobar' user3.email = '*****@*****.**' user3.birthday = datetime.date(1970, 5, 7) user3.is_friendly = True user3.tags = ['relaxed', 'beerfan'] user3.referred_by = user1.oid users.append(user3) with Transaction(env, write=True) as txn: for user in users: _user = txn.users[user.oid] if not _user: txn.users[user.oid] = user #txn.users_by_authid[user.authid] = user.oid print('user stored', user) else: print('user loaded', _user)
def registerUser(username, email, password, zipcode): user = User(username=username, email=email, password=password, zipcode=zipcode) try: db.session.add(user) db.session.commit() return True except Exception as e: print e db.session.rollback() return False
def createSampleUsers(): coords = ip2coords.getCoordsFromIP('131.151.88.173') hobbyist = User( username='******', email='*****@*****.**', password='******', lat=coords[0], lon=coords[1], ) newbie = User( username='******', email='*****@*****.**', password='******', lat=coords[0], lon=coords[1], ) return hobbyist, newbie
def register(): proto = request.get_json() user = User.query.filter_by(username=proto["username"]).first() if user: return jsonify({"STATE": RegisterState.ALREADY.name}) elif not (proto["username"] and proto["password"]): return jsonify({"STATE": RegisterState.EMPTY.name}) else: user = User(username=proto["username"], password=proto["password"]) db.session.add(user) db.session.commit() return jsonify({"STATE": RegisterState.SUCCESS.name})
def register(): json = request.json email = json['email'] password = json['password'] user = User.query.filter_by(email=email).first() if user: raise InvalidApiUsage('User with same email id already exists', 409) else: user = User(email, password) db.session.add(user) db.session.commit() return jsonify({'message': 'Account successfully created'})
def add_user(db_session, data): user = User(username=data['username'], name=data['name'], password=data['password'], score=0, team=None) try: db_session.add(user) db_session.commit() return True, "Successfully added User {}".format(data["username"]) except Exception as e: db_session.rollback() return False, "Could not add User {}; already exists".format( data["username"])
def register(): # IMPORTANT: Encrypt the password for the increased security. encrypted_password = lambda password_as_string: bcrypt.generate_password_hash( password_as_string) if current_user.is_authenticated: return redirect(url_for("index")) form = RegistrationForm(request.form) if request.method == "POST": # Add user to database. if request.form['company_name'] != "": print(f"company user {form} \n") try: new_user = CompanyUser( email=request.form['email'], first_name=request.form['first_name'], last_name=request.form['last_name'], company_name=request.form['company_name'], password=encrypted_password(request.form['password'])) new_user.save() except Exception as e: raise Exception\ (f"Error {e}. \n Couldn't add company user {new_user},\n with following registration form: {form}") else: print(f"normal user {form} \n") try: new_user = User(email=request.form['email'], first_name=request.form['first_name'], last_name=request.form['last_name'], password=encrypted_password( request.form['password'])) new_user.save() except Exception as e: raise Exception\ (f"Error {e}. \n Couldn't add user {new_user},\n with following registration form: {form}") login_user(new_user, remember=True) user = { 'email': new_user.email, 'first_name': new_user.first_name, 'last_name': new_user.last_name, 'company_name': new_user.last_name } response = make_response(json.dumps(user)) response.status_code = 200 print(f"register {response}\n") return response if request.args.get("email"): form.email.data = request.args.get("email") context_dict = {"title": "Register", "form": form, "user": current_user} return render_template("register.html", **context_dict)
async def give_users_to_client(self, client, users_database): data = [] clients_users = await users_database.count_documents( {'client': client.token}) needed_users = max(0, MAX_USERS_PER_CLIENT - clients_users) free_users = users_database.find({'client': None}).limit(needed_users) async for i in free_users: await users_database.update_one( filter={'_id': i['_id']}, update={"$set": { 'client': client.token }}) data.append(User(**i)) await client.send_users(data)
def upsert_user(self, userinfo): user = self.get_user(userinfo['id']) if user: user.email = userinfo['email'] user.name = userinfo['name'] user.avatar = userinfo['picture'] else: user = User(id=int(userinfo['id']), email=userinfo['email'], name=userinfo['name'], avatar=userinfo['picture']) self.db.add(user) self.db.commit() return user
def add_users(): return "nothing to add" users = dbmock.format_mocked_users() encrypted_password = lambda password_as_string: bcrypt.generate_password_hash( password_as_string) for u in users: # Add user to database. try: new_user = User(email=u['email'], first_name=u['first_name'], last_name=u['last_name'], password=encrypted_password(str(u['password'])), is_verified=u["is_verified"]) new_user.save() except: print(f"Error. \n Couldn't add user {u}..\n") print(f"Added {u['first_name'] + ' ' + u['last_name']}") return str(User.objects[:10])
def test_insert2(env): with Transaction(env, write=True) as txn: for i in range(100): user = User() user.oid = i + 10 user.name = 'Test {}'.format(i) user.authid = 'test-{}'.format(i) user.email = '{}@example.com'.format(user.authid) for j in range(10): user.ratings['test-rating-{}'.format(j)] = random.random() _user = txn.users[user.oid] if not _user: txn.users[user.oid] = user #txn.users_by_authid[user.authid] = user.oid print('user stored', user, user.oid, user.authid) else: print('user loaded', _user, _user.oid, _user.authid)
def add_user(fb_id, email, password, name, fb_updated_time, email_verified, uuid=None): user = User(fb_id=fb_id, email=email, password=db.func.md5(password + app.config['SALT']), name=name, fb_updated_time=fb_updated_time, email_verified=email_verified, uuid=uuid) db.session.add(user) db.session.commit() return user
def test_insert3(env): oid = 4 with Transaction(env, write=True) as txn: user = txn.users[oid] if not user: user = User() user.oid = oid user.name = 'Foobar Space' user.authid = 'foobar' user.email = '*****@*****.**' user.birthday = datetime.date(1970, 5, 7) user.is_friendly = True user.tags = ['relaxed', 'beerfan'] user.referred_by = 1 txn.users[oid] = user print('user stored', user) else: print('user loaded', user)
"""using sql alchemy """ from __future__ import absolute_import from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from tornado.web import RequestHandler, Application from schema import User, Base # create engine MySQLdb没有支持python3的版本,如果使用python3.x版本时,需要安装额外的库pymysql engine = create_engine("mysql+pymysql://lsl:123456@localhost:3306/target", encoding='latin1', echo=True) Base.metadata.create_all(engine) Session = sessionmaker() Session.configure(bind=engine) session = Session() # if __name__ == '__main__': ed_user = User(name="ed", fullname="ED Json", nickname="ed_nickname") session.add(ed_user) session.commit()
# Get file names micrograph_metadata_file_name = join(data_dir, 'micro_db.json') sample_metadata_file_name = join(data_dir, 'sample_db.json') user_metadata_file_name = join(data_dir, 'user_db.json') # # Connect to db connect('micrograph_db') # # Load user info with open(user_metadata_file_name, 'r') as user_metadata_file: user_metadata = json.load(user_metadata_file) for k, v in user_metadata.items(): user = User( user_id=int(k), user_name=v['user_name'], first_name=v['first_name'], last_name=v['last_name'], email=v['email'], ).save() # # Load sample info with open(sample_metadata_file_name, 'r') as sample_metadata_file: sample_metadata = json.load(sample_metadata_file) for k, v in sample_metadata.items(): sample = Sample( sample_id=int(k), anneal_temperature=v['anneal_temperature'], anneal_time_units=v['anneal_time_units'], label=v['label'], anneal_time=v['anneal_time'], cooling_method=v['cooling_method'],
from sqlalchemy.orm import Query from db import Base, engine, session from schema import User from sqlalchemy import text, desc Base.metadata.create_all(engine) # usuwanie danych z tabeli session.query(User).delete() session.commit() # dodaj dane do tablicy user1 = User(login="******", password="******", name="Jan Kowalski") user2 = User(login="******", password="******", name="Marek Nowak") user3 = User(login="******", password="******", name="Marek Jurek") session.add(user1) session.add(user2) session.add(user3) session.commit() query: Query = session.query(User) print(query.all()) # pokaż wszystkie rekordy print(query.filter(User.id == 1).scalar()) # pobranie na podstawie warunku print(query.filter(User.id == 1).first()) # pobranie na podstawie warunku print(query.get(1)) # pobranie na podstawie warunku print("=" * 60) print(query.filter(User.login == "jkowalski").all()) print(query.filter_by(login="******").all())
def parse_post(content): post = Post() users = [] comments = [] # Note: this code needs patched lxml with support for huge_tree in HTMLParser parser = lxml.etree.HTMLParser(recover=True, huge_tree=True) root = lxml.etree.HTML(content, parser=parser) # post post_node = root.xpath('//li[@class="hentry"]')[0] comments_node = post_node.xpath('.//div[@class="entry-comments"]')[0] author_node = post_node.xpath('.//p[@class="author"]')[0] post_url = post_node.xpath('.//a[@class="entry-title"]')[0].get('href') post.post_id = int(re.search(r'/(\d+)$', post_url).group(1)) comment_list_raw = comments_node.xpath('ul')[0].get("id") post.comment_list_id = int(re.match(r'comments_(\d+)$', comment_list_raw).group(1)) post.language = post_node.xpath('.//a[@rel="chapter"]')[0].text post.code = post_node.xpath('div[@class="entry-content"]/pre/code')[0].text post.text = inner_html(post_node.xpath('p[@class="description"]')[0]) post.posted = parse_date(author_node.xpath('abbr')[0].get('title')) post.vote_plus, post.vote_minus, post.rating = parse_rating(post_node.xpath('p[@class="vote"]/strong')[0]) # author info user = User() user_url = author_node.xpath('a[1]')[0].get('href') user.user_id = int(re.search(r'/user/(\d+)$', user_url).group(1)) user.name = author_node.xpath('a[2]')[0].text user.avatar_hash = parse_avatar(author_node.xpath('a[1]/img')[0].get('src')) post.user_id = user.user_id users.append(user) # comments for comment_node in comments_node.xpath('.//div[@class="entry-comment-wrapper"]'): comment = Comment() comment.comment_id = int(re.match(r'comment-(\d+)$', comment_node.get('id')).group(1)) comment.post_id = post.post_id parent_node = comment_node.getparent().getparent().getparent() if parent_node.tag == 'li': parent_node = parent_node.xpath('div[@class="entry-comment-wrapper"]')[0] comment.parent_id = int(re.match(r'comment-(\d+)$', parent_node.get('id')).group(1)) else: comment.parent_id = None comment.text = inner_html(comment_node.xpath('.//span[@class="comment-text"]')[0]) info_node = comment_node.xpath('p[@class="entry-info"]')[0] comment.posted = parse_date(info_node.xpath('abbr[@class="published"]')[0].get('title')) comment.vote_plus, comment.vote_minus, comment.rating = parse_rating(info_node.xpath('span[@class="comment-vote"]/strong')[0]) user_node = info_node.xpath('strong[@class="entry-author"]/a')[0] user = User() user.user_id = int(re.search(r'/user/(\d+)$', user_node.get('href')).group(1)) user.name = user_node.text user.avatar_hash = parse_avatar(info_node.xpath('img[@class="avatar"]')[0].get('src')) comment.user_id = user.user_id users.append(user) comments.append(comment) return (post, users, comments)
def main(config): config = get_config(config) teardown(drop_db=False, config=config) documents = json.load(open(config)) engine = pg_engine( database=documents[0].get("database", documents[0]["index"])) Session = sessionmaker(bind=engine, autoflush=True) session = Session() # Bootstrap users = { "Carla Ferreira Cardoso": User(name="Carla Ferreira Cardoso", age=19, gender="female"), "Uwe Fuerst": User(name="Uwe Fuerst", age=58, gender="male"), "Otitodilinna Chigolum": User(name="Otitodilinna Chigolum", age=36, gender="male"), } with subtransactions(session): session.add_all(users.values()) posts = { "Post 1": Post(slug="post_1", title="This is the first post"), "Post 2": Post(slug="post_2", title="This is the second post"), "Post 3": Post(slug="post_3", title="This is the third post"), } with subtransactions(session): session.add_all(posts.values()) comments = { "Comment 1": Comment( title="Comment 1", content="This is a sample comment for comment 1", ), "Comment 2": Comment( title="Comment 2", content="This is a sample comment for comment 2", ), "Comment 3": Comment( title="Comment 3", content="This is a sample comment for comment 3", ), "Comment 4": Comment( title="Comment 4", content="This is a sample comment for comment 4", ), "Comment 5": Comment( title="Comment 5", content="This is a sample comment for comment 5", ), "Comment 6": Comment( title="Comment 6", content="This is a sample comment for comment 6", ), } with subtransactions(session): session.add_all(comments.values()) tags = { "Economics": Tag(name="Economics"), "Career": Tag(name="Career"), "Political": Tag(name="Political"), "Fitness": Tag(name="Fitness"), "Entertainment": Tag(name="Entertainment"), "Education": Tag(name="Education"), "Technology": Tag(name="Technology"), "Health": Tag(name="Health"), "Fashion": Tag(name="Fashion"), "Design": Tag(name="Design"), "Photography": Tag(name="Photography"), "Lifestyle": Tag(name="Lifestyle"), } with subtransactions(session): session.add_all(tags.values()) user_posts = [ UserPost( user=users["Carla Ferreira Cardoso"], post=posts["Post 1"], ), UserPost( user=users["Uwe Fuerst"], post=posts["Post 2"], ), UserPost( user=users["Otitodilinna Chigolum"], post=posts["Post 3"], ), ] with subtransactions(session): session.add_all(user_posts) user_tags = [ UserTag( user=users["Carla Ferreira Cardoso"], tag=tags["Economics"], ), UserTag( user=users["Carla Ferreira Cardoso"], tag=tags["Career"], ), UserTag( user=users["Carla Ferreira Cardoso"], tag=tags["Political"], ), UserTag( user=users["Carla Ferreira Cardoso"], tag=tags["Lifestyle"], ), UserTag( user=users["Carla Ferreira Cardoso"], tag=tags["Health"], ), UserTag( user=users["Uwe Fuerst"], tag=tags["Education"], ), UserTag( user=users["Uwe Fuerst"], tag=tags["Lifestyle"], ), UserTag( user=users["Otitodilinna Chigolum"], tag=tags["Fashion"], ), ] with subtransactions(session): session.add_all(user_tags) post_comments = [ PostComment( post=posts["Post 1"], comment=comments["Comment 1"], ), PostComment( post=posts["Post 1"], comment=comments["Comment 2"], ), PostComment( post=posts["Post 2"], comment=comments["Comment 3"], ), PostComment( post=posts["Post 2"], comment=comments["Comment 4"], ), PostComment( post=posts["Post 3"], comment=comments["Comment 5"], ), PostComment( post=posts["Post 3"], comment=comments["Comment 6"], ), ] with subtransactions(session): session.add_all(post_comments)
async def main(): async with async_session() as session: ed_user = User(name='ed') session.add(ed_user) await session.commit()
def post(self): parser = reqparse.RequestParser() parser.add_argument( 'firstName', help="First name of user", required=True, ) parser.add_argument( 'lastName', help="Last name of user", required=True, ) parser.add_argument( 'email', help="User's email address", required=True, ) parser.add_argument( 'password', help="Password", required=True, ) parser.add_argument( 'lat', type=float, help="User's location (latitude decimal degrees)", ) parser.add_argument( 'lon', type=float, help="User's location (longitude decimal degrees)", ) args = parser.parse_args() print(request.form) firstName = args['firstName'] #request.form['firstName'] lastName = args['lastName'] #request.form['lastName'] email = args['email'] #request.form['email'] password = args['password'] #request.form['password'] """ if "lat" in request.form and "long" in request.form: lat = request.form.get('lat', type=float) lon = request.form.get('lon', type=float) """ lat = args['lat'] lon = args['lon'] if lat is None: lat = 35.4 lon = -91.33 try: new_user = User( f=firstName, l=lastName, email=email, password=password, lat=lat, lon=lon, ) db.session.add(new_user) db.session.commit() _id = User.query.filter_by(email=email).first().id return {'user_id': _id} except: return {"status": "Error"}
def main(config): config = get_config(config) teardown(drop_db=False, config=config) document = json.load(open(config)) engine = pg_engine( database=document[0].get('database', document[0]['index'])) Session = sessionmaker(bind=engine, autoflush=True) session = Session() # Bootstrap users = { 'Carla Ferreira Cardoso': User(name='Carla Ferreira Cardoso', age=19, gender='female'), 'Uwe Fuerst': User(name='Uwe Fuerst', age=58, gender='male'), 'Otitodilinna Chigolum': User(name='Otitodilinna Chigolum', age=36, gender='male'), } with subtransactions(session): session.add_all(users.values()) posts = { 'Post1': Post(slug='post_1', title='This is the first post'), 'Post2': Post(slug='post_2', title='This is the second post'), 'Post3': Post(slug='post_3', title='This is the third post'), } with subtransactions(session): session.add_all(posts.values()) comments = { 'Comment1': Comment( title='Comment 1', content='This is a sample comment for comment 1', ), 'Comment2': Comment( title='Comment 2', content='This is a sample comment for comment 2', ), 'Comment3': Comment( title='Comment 3', content='This is a sample comment for comment 3', ), 'Comment4': Comment( title='Comment 4', content='This is a sample comment for comment 4', ), 'Comment5': Comment( title='Comment 5', content='This is a sample comment for comment 5', ), 'Comment6': Comment( title='Comment 6', content='This is a sample comment for comment 6', ), } with subtransactions(session): session.add_all(comments.values()) tags = { 'Economics': Tag(name='Economics'), 'Career': Tag(name='Career'), 'Political': Tag(name='Political'), 'Fitness': Tag(name='Fitness'), 'Entertainment': Tag(name='Entertainment'), 'Education': Tag(name='Education'), 'Technology': Tag(name='Technology'), 'Health': Tag(name='Health'), 'Fashion': Tag(name='Fashion'), 'Design': Tag(name='Design'), 'Photography': Tag(name='Photography'), 'Lifestyle': Tag(name='Lifestyle'), } with subtransactions(session): session.add_all(tags.values()) user_posts = [ UserPost( user=users['Carla Ferreira Cardoso'], post=posts['Post1'], ), UserPost( user=users['Uwe Fuerst'], post=posts['Post2'], ), UserPost( user=users['Otitodilinna Chigolum'], post=posts['Post3'], ), ] with subtransactions(session): session.add_all(user_posts) user_tags = [ UserTag( user=users['Carla Ferreira Cardoso'], tag=tags['Economics'], ), UserTag( user=users['Carla Ferreira Cardoso'], tag=tags['Career'], ), UserTag( user=users['Carla Ferreira Cardoso'], tag=tags['Political'], ), UserTag( user=users['Carla Ferreira Cardoso'], tag=tags['Lifestyle'], ), UserTag( user=users['Carla Ferreira Cardoso'], tag=tags['Health'], ), UserTag( user=users['Uwe Fuerst'], tag=tags['Education'], ), UserTag( user=users['Uwe Fuerst'], tag=tags['Lifestyle'], ), UserTag( user=users['Otitodilinna Chigolum'], tag=tags['Fashion'], ), ] with subtransactions(session): session.add_all(user_tags) post_comments = [ PostComment( post=posts['Post1'], comment=comments['Comment1'], ), PostComment( post=posts['Post1'], comment=comments['Comment2'], ), PostComment( post=posts['Post2'], comment=comments['Comment3'], ), PostComment( post=posts['Post2'], comment=comments['Comment4'], ), PostComment( post=posts['Post3'], comment=comments['Comment5'], ), PostComment( post=posts['Post3'], comment=comments['Comment6'], ), ] with subtransactions(session): session.add_all(post_comments)
import sys sys.path.append('../helpers/') from schema import Base, City, Startup, User from database_helpers import create_session session = create_session('sqlite:///startup.db') user_1 = User(username='******', email='*****@*****.**') user_2 = User(username='******', email='*****@*****.**') session.bulk_save_objects([user_1, user_2]) session.commit() user_1 = session.query(User).filter_by(email='*****@*****.**').first() cities = [ City(name='New York', slug='new-york', state='ny'), City(name='San Francisco', slug='san-francisco', state='ca'), City(name='Chicago', slug='chicago', state='il'), City(name='Portland', slug='portland', state='or'), City(name='Seattle', slug='seattle', state='wa'), City(name='Asheville', slug='asheville', state='nc'), City(name='Boston', slug='boston', state='ma') ] session.bulk_save_objects(cities) session.commit() nyc = session.query(City).filter_by(name='New York').one() chi = session.query(City).filter_by(name='Chicago').one()