def oauth_callback(provider): if not current_user.is_anonymous: return redirect(url_for('index')) oauth = OAuthSignIn.get_provider(provider) username, email, picture, source = oauth.callback() if email is None: # I need a valid email address for my user identification flash('Authentication failed.') return redirect(url_for('index')) # Look if the user already exists user = session.query(User).filter_by(email=email).first() if not user: # Create the user. Try and use their name returned by Google, # but if it is not set, split the email address at the @. nickname = username if nickname is None or nickname == "": nickname = email.split('@')[0] print "nickname: ", nickname # We can do more work here to ensure a unique nickname, if you # require that. user = User(username=nickname, email=email, picture=picture, user_source=source) session.add(user) session.commit() # Log in the user, by default remembering them for their next visit # unless they log out. user.last_login_date = datetime.utcnow() session.add(user) session.commit() login_user(user, remember=False) return redirect(url_for('index'))
def post(self): # One can only delete themselves, if they are logged in and post with a # vaild state if not self.request.form.get("csrf") == session.get('state'): return self.flash_out( "The state does not match the session, please try again", 401, url_for("myaccount_view")) # Get the user id from session uid = session.get('uid') if not uid: self.auth.logout() return self.flash_out( "No valid login detected", 401, url_for("login_view")) # Revoke the access token for the provider provider = session.get('provider') if provider == "google": self.google.disconnect() elif provider == 'facebook': self.facebook.disconnect() # Delete all the items that belong to the user Items.delete_by_user(dbs, uid) # Delete the user's image Images.delete_by_id(dbs, self.user.picture) # Delete the user User.delete_user(dbs, uid) self.auth.logout() return self.flash_out("The account has been deleted", 200, "/")
def register_user(): email = request.form.get('email') if not re.match(email_pattern, email): return jsonify(message="Email is not valid."), 400 password = request.form.get('password') username = request.form.get('username') if email == '' or password == '' or username == '': return jsonify(message='Form fields incomplete.'), 400 if session.query(User).filter_by(email=email).first() is not None: return jsonify(message='User already registered.'), 400 # initialize user user = User(email=email) user.username = username user.hash_password(password) user.picture = default_picture_url session.add(user) session.commit() # set login_session data user = session.query(User).filter_by(email=email).one() login_session['username'] = user.username login_session['email'] = user.email login_session['picture'] = user.picture login_session['user_id'] = user.id login_session['provider'] = 'none' return jsonify(message='You have successfully registered.'), 201
def db_update_user(db_session, login_session): # if user is not already in db: # insert into db user_id = login_session['id'] user = db_session.query(User).filter_by(id=user_id).all() if not user: user = User() user.id = user_id db_session.add(user) db_session.commit()
def test_make_unique_nickname(self): u = User(name='john', email='*****@*****.**', picture="") self.db.session.add(u) self.db.session.commit() nickname = User.make_unique_nickname('john', self.db.session) assert nickname != 'john' u = User(name=nickname, email='*****@*****.**', picture="") self.db.session.add(u) self.db.session.commit() nickname2 = User.make_unique_nickname('john', self.db.session) assert nickname2 != 'john' assert nickname2 != nickname
def do_login(): print 'step: do_login() with request method - ', request.method user = None _is_authenticated = False try: if request.method == 'GET': if 'user_id' in session: user = User.get_by_id(get_user_id_from_session()) if user is None: raise print 'user %s is not existing.' % get_user_id_from_session() else: _is_authenticated = check_signin() print 'user exists' elif request.method == 'POST': #Check e-mail email = request.form['email'] if validate_email(email) == None: flash('This e-mail address is invalid.', 'error') raise user = User.get_by_id(email) if user is None: flash('This e-mail is not registered.', 'error') raise #Check password if user.verify_password(request.form['password']) == False: flash('Password is invalid!', 'error') raise session['user_id'] = email _is_authenticated = True except: session.pop('user_id', None) finally: if _is_authenticated == True: print '<authenticated>' response = make_response(redirect_common(url_for('user.myaccount'))) key_random = urandom(24) session['random_auth'] = hmac_new(key_random, get_user_id_from_session()).hexdigest() response.set_cookie('random_auth', session['random_auth']) return response else: print '<NOT authenticated>' return render_template('login.html', email = get_user_id_from_session())
def get(self, uid): my_user = User.get_by_id(dbs, uid) if not my_user: return self.flash_out("No user found", 404, "/") user_items = Items.get_all_by_user(dbs, uid) for item in user_items: item.uname = my_user.name return self.render_template( "user_view.html", my_user=my_user, items=user_items)
def get_user_by_session(self): """ Returns the session user, by querying the db for the user id found in session """ uid = session.get("uid") if not uid: return None myuser = User.get_by_id(dbs, uid) if not myuser: return None return myuser
def authorized(oauth_token): next_url = request.args.get('next') or url_for('showCatalog') if oauth_token is None: # something went wront flash("Authorization failed") flash(request.args.get('error')) flash(request.args.get('error_description')) flash(request.args.get('error_uri')) return redirect(next_url) user = User.query.filter_by(github_access_token=oauth_token).first() if user is None: # new user is not in database user = User(name="",github_access_token=oauth_token) db_session.add(user) # save oauth token in database user.github_access_token = oauth_token db_session.commit() session['user_id'] = user.id flash("User " + user.name + " logged in") return redirect(next_url)
def authorized(oauth_token): next_url = request.args.get('next') or url_for('index') if oauth_token is None: flash('Authorization failed.', 'alert') return redirect(next_url) user = db_session.query(User).filter_by(access_token=oauth_token).first() if user is None: user = User(oauth_token) db_session.add(user) user.access_token = oauth_token db_session.commit() # Store current user details in a session session['usr_id'] = user.id session['usr_token'] = user.access_token flash('Logged in', 'success') return redirect(url_for('index'))
def usersXML(): """ ####Returns#### + users: XML object of all users """ root = ET.Element('users') return app.response_class( ET.tostring( User.getUsersXML(session, root), encoding='us-ascii', method='xml'), mimetype='application/xml')
def authorized(oauth_token): """ callback from github oauth """ next_url = request.args.get('next') if oauth_token is None: flash('Authorization failed.', 'danger') return redirect(next_url) user = db_session.query(User).filter_by(access_token=oauth_token).first() if user is None: user = User(oauth_token) db_session.add(user) # store access token into database user.access_token = oauth_token db_session.commit() # store user id and access token in session hash session['user_id'] = user.id session['user_token'] = user.access_token flash('You\'re logged in! Now you have incredible superpowers...', 'success') return redirect(url_for('index'))
def oauth2callback(token, userinfo, **params): """The Oauth2 callback from Flask-GoogleLogin""" id = str(userinfo['id']) name = userinfo['name'].strip() changed = False user = session.query(User).filter_by(id=id).first() if not user: user = User(id=id, name=name) changed = True elif user.name != name: user.name = name changed = True if changed: session.add(user) session.commit() login_user(user, remember=True) return redirect(request.args.get("next") or url_for("latestItems"))
def get(self, category, item_id): category = category.title() my_item = Items.get_by_id(dbs, item_id) if not my_item: return self.flash_out( "The item you are looking for does not exist", 404, "/") owner = User.get_by_id(dbs, my_item.user_id) # This really shouldn't happen but it's good to account for this # possibility if not owner: return self.flash_out( "Something went wrong, try again, if the problem persists contact us!", 500, "/") return self.render_template("item.html", my_category=category, owner=owner, my_item=my_item, categories=other_info.item_categories)
def inject_context(): print 'inject_context' user = User.get_by_id(get_user_id_from_session()) if user is None: print 'failed to inject user.' user = User() else: print 'successful to inject user.' def check_signin_in_template(): print 'step: check_signin_in_template().' return check_signin() def redirect_in_template(last_path): return redirect_common(last_path, just_path = True) return dict(current_user = user, \ redirect_in_template = redirect_in_template, \ check_signin_in_template = check_signin_in_template)
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, Category, Item, User, engine Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() default_user = User(id=1, name="Default User", email="*****@*****.**") session.add(default_user) category1 = Category(id=1, name='Soccer') category2 = Category(id=2, name='Basketball') category3 = Category(id=3, name='Baseball') category4 = Category(id=4, name='Frisbee') category5 = Category(id=5, name='Snowboarding') category6 = Category(id=6, name='Rock Climbing') category7 = Category(id=7, name='Foosball') category8 = Category(id=8, name='Skating') category9 = Category(id=9, name='Hockey') session.add(category1) session.add(category2) session.add(category3) session.add(category4) session.add(category5) session.add(category6) session.add(category7)
# declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create test user User1 = User(name="Abigail Seligsteinstein", email="*****@*****.**", picture='') session.add(User1) session.commit() #Items for Carpenter category1 = Categories(name="Carpentry", user_id=1) session.add(category1) session.commit() item1 = Items( user_id=1, name="Claw Hammer", description=
# declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create dummy user User1 = User(name="Jerry Woods", email="*****@*****.**", picture="/static/img/user_1.jpg") session.add(User1) session.commit() # Create Countries countries = [{"id": "1", "name": "United States Of America"}] for country in countries: newCountry = Country(id=country["id"], name=country["name"]) session.add(newCountry) session.commit() # Create states/regions regions = [{ "country_id": "1",
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, User, Phylum, Class, Order, Family, Genus, Species, PhylumClass, ClassOrder, OrderFamily, FamilyGenus, GenusSpecies engine = create_engine('sqlite:///fungusamongus.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # Load Admin User session.query(User).delete() session.commit() admin = User() admin.user_id = 1 admin.user_name = 'admin' admin.user_email = '*****@*****.**' session.add(admin) session.commit() # Load Phylum session.query(Phylum).delete() session.commit() phylums = open('phylum.json') phylum_data = json.load(phylums) for phylum in phylum_data: phylum_entry = Phylum() phylum_entry.phylum_name = phylum['PhylumName']
DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create dummy user User1 = User( name="Atefeh Mohammadi", email="*****@*****.**", picture="https://www.neatorama.com/images/" + "2014-06/mobile-relationship-manu-cornet.jpg", ) session.add(User1) session.commit() genre1 = Genre(user_id=1, name="Comedy") session.add(genre1) session.commit() genre2 = Genre(user_id=1, name="Sci-Fi") session.add(genre2) session.commit() genre3 = Genre(user_id=1, name="Horror") session.add(genre3)
Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # create a user User1 = User( name="Radhika", email="*****@*****.**", picture= 'http://ragamuffinsbazaar.co.uk/wp-content/uploads/2014/10/RS-Logo-Outline.png' ) session.add(User1) session.commit() #Menu for Tex Foods restaurant1 = Restaurant(user_id=1, name="Tex Foods") session.add(restaurant1) session.commit() menuItem1 = MenuItem(user_id=1, name="French Fries", description="with garlic and parmesan", price="$2.99",
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, User, Item, Category engine = create_engine('sqlite:///catalog.db') #engine = create_engine('postgresql://*****:*****@localhost/catalog') Base.metadata.bind=engine DBSession = sessionmaker(bind = engine) session = DBSession() firstUser = User(name="Jester Thomas", email="*****@*****.**", picture="https://upload.wikimedia.org/wikipedia/commons/1/1e/David-Bowie_Early.jpg") session.add(firstUser) session.commit() firstCat = Category(name="David Bowie", user_id=firstUser.id) session.add(firstCat) session.commit() item1 = Item(name='Ziggy Stardust and the Spiders From Mars', year=1972, icon='https://upload.wikimedia.org/wikipedia/en/0/01/ZiggyStardust.jpg', description="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus eget quam non nulla sodales laoreet. Etiam nec ipsum ac velit laoreet sodales. Sed efficitur hendrerit risus ut suscipit. Morbi vel nulla in urna cursus varius. Curabitur facilisis, tellus ut scelerisque mollis, est augue lacinia lorem, at imperdiet urna tortor ac felis. Etiam efficitur quam eget felis lacinia, eu pretium ligula maximus. Donec est ex, molestie quis ultrices sed, hendrerit id nibh.", category_id=firstCat.id, user_id=firstUser.id) session.add(item1) session.commit() item5 = Item(name='Station to Station', year=1976, icon='https://upload.wikimedia.org/wikipedia/en/9/97/Station_to_Station_cover.jpg', description="Cras in erat nulla. Donec vestibulum gravida leo, eget ultrices sapien maximus non. Duis varius vitae massa vitae varius. Phasellus ornare risus ac maximus ullamcorper. Nulla congue lacus vitae est faucibus iaculis ac a ex. Mauris id suscipit lacus. Aliquam neque tortor, cursus ut vehicula a, porttitor cursus nibh. Sed et nunc quam. Ut dignissim, mi ac ultricies mattis, arcu purus blandit enim, non iaculis erat sapien sed tellus. Nulla facilisi. Pellentesque non tempus lectus. Duis molestie sapien in leo fermentum, lobortis eleifend felis pharetra. Donec vel mollis ex, ac congue sem.", category_id=firstCat.id, user_id=firstUser.id) session.add(item5) session.commit() item6 = Item(name='Heroes', year=1977, icon='https://upload.wikimedia.org/wikipedia/en/7/7b/David_Bowie_-_Heroes.png', description="In nec dictum odio, sit amet rutrum justo. Cras eget gravida dolor, vitae facilisis elit. Nullam nec consectetur quam, et rutrum nibh. Proin sed dapibus elit. Integer ultrices, augue in faucibus consectetur, neque felis iaculis sapien, vel scelerisque dui neque eget arcu. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras quam eros, rhoncus finibus lacus ac, sollicitudin egestas lectus. Cras vitae tristique massa. Curabitur at nibh ultricies, fermentum eros vitae, venenatis arcu. Nunc sodales interdum dui sit amet rhoncus. Integer tempor et eros ac tempor.", category_id=firstCat.id, user_id=firstUser.id) session.add(item6) session.commit() item7 = Item(name="Low", year=1977, icon='https://upload.wikimedia.org/wikipedia/en/9/93/Low_%28album%29.jpg', description="Aliquam erat volutpat. In blandit dolor at aliquam pulvinar. Donec interdum diam nulla, eget iaculis eros efficitur id. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nam ornare, justo eget hendrerit interdum, libero turpis elementum odio, vitae tincidunt purus lorem nec libero. Phasellus in erat vestibulum, ullamcorper purus eu, elementum urna. Vestibulum vel lectus molestie erat congue lobortis sed a nulla. Ut luctus et sem vitae dictum. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi fermentum libero ut lacinia fringilla. Praesent tellus arcu, sodales vitae erat quis, placerat tincidunt tellus.", category_id=firstCat.id, user_id=firstUser.id)
def login(provider): """Login to the system using third party provider (Google)""" # STEP 1 - Parse the auth code # auth_code = request.json.get('auth_code') auth_code = request.data print "Step 1 - Complete, received auth code %s" % auth_code if provider == 'google': # STEP 2 - Exchange for a token try: # Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(auth_code) except FlowExchangeError: response = make_response( json.dumps('Failed to upgrade the ' + 'authorization code.'), 401) response.headers['Content-Type'] = 'application/json' return response # Check that the access token is valid. access_token = credentials.access_token url = ( 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) h = httplib2.Http() result = json.loads(h.request(url, 'GET')[1]) # If there was an error in the access token info, abort. if result.get('error') is not None: response = make_response(json.dumps(result.get('error')), 500) response.headers['Content-Type'] = 'application/json' print "Step 2 Complete! Access Token : %s " % credentials.access_token # STEP 3 - Find User or make a new one # Get user info h = httplib2.Http() userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() name = data['name'] picture = data['picture'] email = data['email'] # See if user exists, if it doesn't make a new one user = session.query(User).filter_by(email=email).first() if not user: user = User(username=name, picture=picture, email=email) session.add(user) session.commit() # STEP 4 - Make token token = user.generate_auth_token(600) flask_session['user_id'] = user.id flask_session['username'] = user.username flask_session['email'] = user.email flask_session['logged_in'] = True # STEP 5 - Send back token to the client return jsonify({'token': token.decode('ascii')}) else: return 'Unrecoginized Provider'
# Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create dummy user user1 = User(name="Srinu", email="*****@*****.**") session.add(user1) session.commit() # Items for Strings category1 = Category(name="strings", user_id=1) session.add(category1) session.commit() item1 = CategoryItem( name="violin", user_id=1, description= "Violin, family of stringed musical instruments having wooden bodies whose backs and fronts are slightly convex, the fronts pierced by two-shaped resonance holes. The instruments of the violin family have been the dominant bowed instruments because of their versatility, brilliance, and balance of tone, and their wide dynamic range. A variety of sounds may be produced, e.g., by different types of bowing or by plucking the string (see pizzicato). The violin has always been the most important member of the family, from the beginning being the principal orchestral instrument and holding an equivalent position in chamber music and as a solo instrument. The technique of the violin was developed much earlier than that of the viola or cello.", category=category1)
declaratives can be accessed through a DBSession instance""" Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) """A DBSession() instance establishes all conversations with the database and represents a "staging zone" for all the objects loaded into the database session object. Any change made against the objects in the session won't be persisted into the database until you call session.commit(). If you're not happy about the changes, you can revert all of them back to the last commit by calling session.rollback()""" session = DBSession() """Create user""" User1 = User(name="Lavanya", email="*****@*****.**", picture='https://lh6.googleusercontent.com' '/-ODf1V0QoS2Q/AAAAAAAAAAI/AAAAAAAAAAA/' 'saglyR2exWU/W96-H96/photo.jpg') session.add(User1) session.commit() """Menu for Baristas""" coffeeshop1 = Coffeeshop(user_id=1, name="Baristas") session.add(coffeeshop1) session.commit() menuItem1 = MenuItem(user_id=1, name="Espresso", description='''The espresso (aka short black) is the foundation and the most important part to every espresso based drink mayo and lettuce''', price="$7.50",
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, User, Category, Item engine = create_engine('sqlite:///catalog.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # Create two users user_one = User(name="Pavel Nedved", email="*****@*****.**") session.add(user_one) session.commit() user_one = session.query(User).filter_by(email=user_one.email).one() user_two = User(name="Hristo Junior", email="*****@*****.**") session.add(user_two) session.commit() user_two = session.query(User).filter_by(email=user_two.email).one() # Create two categories for each user category_one = Category(title="Soccer", user_id=user_one.id) session.add(category_one) session.commit() category_one = session.query(Category).filter_by(
# Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create dummy user User1 = User(name="admin", email="*****@*****.**") session.add(User1) session.commit() # Menu for Rajula's Kitchen restaurant1 = Restaurant(name="Rajula's Kitchen", user_id="1") session.add(restaurant1) session.commit() menuItem1 = MenuItem(name="Masala Dosa", description="Crepe made from rice" "batter and black lentils.", price="$2.99", restaurant=restaurant1, user_id=1) session.add(menuItem1)
medical="bad") session.add(form1) form2 = Form(first_name="Jonny", last_name="Bravo", roll='1010102', email_id='*****@*****.**', accomodation="good", food="bad", clean="good", complain="bad", behaviour="very good", medical="bad") session.add(form2) form3 = Form(first_name="Shinchan", last_name="Cartoon", roll='1010102', email_id='*****@*****.**', accomodation="good", food="good", clean="good", complain="bad", behaviour="awesome", medical="not good") session.add(form3) user1 = User(name="Admin", email="*****@*****.**") session.add(user1) user2 = User(name="President", email="*****@*****.**") session.add(user2) session.commit()
# declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create Admin user User1 = User(name="Hany Salama", email="*****@*****.**", picture='https://secure.gravatar.com/avatar/0fe8828052a5d3351f24fd0a80365303.jpg?s=512&r=g&d=mm', user_type=2) session.add(User1) session.commit() # Menu for UrbanBurger restaurant1 = Restaurant(user_id=1, name="Urban Burger") session.add(restaurant1) session.commit() menuItem2 = MenuItem(user_id=1, name="Veggie Burger", description="Juicy grilled veggie patty with tomato mayo and lettuce", price="$7.50", course="Entree", restaurant=restaurant1) session.add(menuItem2) session.commit()
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Genre, Base, Movie, User engine = create_engine('sqlite:///movieswithusers.db') # Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bing = engine DBSession = sessionmaker(bind=engine) # Establishes connection to database in the form of a staging area session = DBSession() # Dummy user User1 = User(name="Koda Bot", email="*****@*****.**") session.add(User1) session.commit() # Movies for Comedy genre1 = Genre( user_id=1, name="Comedy", description="""Comedy's main emphasis is on humor, and are designed to make the audience laugh. These movies typically have happy endings.""") session.add(genre1) session.commit() movie1 = Movie(user_id=1,
def load_user(id): return User.get(id)
# declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create dummy user User1 = User(name="User One", email="*****@*****.**", picture="https://pbs.twimg.com/profile_images/" "2671170543/18debd694829ed78203a5a36dd364160_400x400.png") session.add(User1) session.commit() # Create category for Faith category1 = Category(user_id=1, name="Faith") session.add(category1) session.commit() categoryItem1 = CategoryItem(user_id=1, name="Psalm 9:10", description="Those who know your name trust in " "you, for you, LORD, have never forsaken those " "who seek you.",
# declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create dummy user User1 = User(name="Robo Barista", email="*****@*****.**", photo='https://pbs.twimg.com/profile_images/2671170543/18debd694829ed78203a5a36dd364160_400x400.png') session.add(User1) session.commit() # Recipes for Breakfast category1 = Category(user_id=1, title="Breakfast") session.add(category1) session.commit() item1 = Item(user_id=1, title="Chicken Orzo Dinner", description= "Although this recipe\u2019s zucchini and tomato medley is a side, it takes center stage in our eyes. It\u2019s equally as creamy as it is crispy, and the combination of panko, mozzarella, and Parmesan sprinkled on top is to thank for that. Served next to an herbed chicken breast and lemony orzo that keep things simple and satisfying, this meal keeps it light without lacking in flavor.", ingredients ="jhgfkdlkgnjhlf;ds'fmkgm;d'ldsfmkglf", instructions = "fdghffgfdsadfghjfhghfds", difficulty = "Easy", serves = 3, preparingTime = '11', cookingTime = '60', picture='https://res.cloudinary.com/hellofresh/image/upload/f_auto,fl_lossy,q_auto/v1/hellofresh_s3/image/mediterranean-chicken-cutlets-dd31b814.jpg',
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, User, Category, Item db_string = "postgres://*****:*****@localhost/catalog_app" engine = create_engine(db_string) Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # Create users user1 = User(name="Heather Weber", email="*****@*****.**") session.add(user1) user2 = User(name="Jesse Walker", email="*****@*****.**") session.add(user2) session.commit() # Create baseball category category = Category(name="Baseball") session.add(category) session.commit() # Create items for baseball item1 = Item(user_id=1, category_name="Baseball", name="Youth Bat",
def googlesignin(): print 'step: googlesignin' token = request.form['idtoken'] if token == None: print 'token is none.' return 'False' else: print 'token is available.' session['signin_party'] = 'google' result, idinfo = get_info_from_google(token) if result == False: print 'googlesignin: failed to get info from google.' session.pop('signin_party', None) return 'False' user = User.get_by_id(idinfo['email']) if user == None: print 'googlesingin: It is new user.' user = User() user.id = idinfo['email'] user.first_name = idinfo['given_name'] user.last_name = idinfo['family_name'] user.add() else: print 'googlesingin: It is NOT new user.' user.id = idinfo['email'] user.first_name = idinfo['given_name'] user.last_name = idinfo['family_name'] user.merge() print user.commit() session['user_id'] = user.id session['token'] = token session['signin_party'] = 'google' return 'True'
# declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create dummy user User1 = User(name="Robo Barista", email="*****@*****.**", picture='https://pbs.twimg.com/profile_images/2671170543/18debd694829ed78203a5a36dd364160_400x400.png') User1.hash_password('12345') session.add(User1) session.commit() # Items for Soccer category1 = Category(user_id=1, name="Soccer") session.add(category1) session.commit() item1 = Item(user_id=1, name="Two shinguards", description="Two shinguards description", category=category1) session.add(item1) session.commit()
session.add(category) session.commit() category = Category(name="Skating") session.add(category) session.commit() category = Category(name="Hockey") session.add(category) session.commit() print "Categories added to the Database." # Add users to database. user = User(name="Happy Me", email="*****@*****.**", picture="https://lh6.googleusercontent.com/-9uyq2wbdVds" "/AAAAAAAAAAI/AAAAAAAAAzU/mqoVFU7zoIA/photo.jpg") session.add(user) session.commit() user = User(name="Hello World", email="*****@*****.**", picture="https://d125fmws0bore1.cloudfront.net/assets" "/udacity_share-317a7f82552763598a5c91e1550b" "7cd83663ce02d6d475d703e25a873cd3b574.png") session.add(user) session.commit() user = User(name="Happy Me", email="*****@*****.**", picture="http://www.softsciencewebmedia.com/images/" "WebTraining_Udacity.png") session.add(user)
engine = create_engine('sqlite:///music.db') # Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() user1 = User(id=1, name="will", email="will.email.com") #Playlist for Rock genre1 = Genre(name="Rock", user=user1) session.add(genre1) session.commit() song1 = Song(name="Mr. Brightside", artist="The Killers", album="Hot Fuss", genre=genre1, user=user1) session.add(song1) session.commit() song2 = Song(name="Seven Nation Army",
#q = session.query(Item).all() #print [i.serialize for i in q] #sys.exit() #q = session.query(Item).order_by(asc(Item.name)).all() #print [i.serialize for i in q] #sys.exit() users = [ ('Bob Whatever', '', '*****@*****.**'), ('Billy Sam', '', '*****@*****.**') ] for name, picture, email in users: session.add(User(username = name, picture = picture, email = email)) session.commit() q = session.query(User).filter_by(email='*****@*****.**').one() #q = session.query(User).filter_by(email='*****@*****.**').first() user1 = q.id q = session.query(User).filter_by(email='*****@*****.**').one() user2 = q.id categories_tuples = [ ('Soccer', [('Shinguards', 'blahblah1', user1), ('Cleats', 'blahblahb2', user2), ('Soccer Ball', 'foofoo', user1)]), ('Basketball', [('Headband', 'blahblah3', user1), ('Basketball Shoes', 'blahblah4', user1), ('Basketball', 'blahblah5', user2)]), #('Baseball', ['Bat', 'Glove', 'Ball']), #('Football', ['Helmet', 'Jersey', 'Shoulder Pads'])
def do_POST(self): try: if self.path.endswith('/logout'): res = self.check_login() if res is not 'NotLoggedIn': id = session.query(User).filter_by(username = res).one().id session.query(LoginSessions).filter_by(user_id = id).delete() session.commit() self.send_response(302) self.send_header('content-type','text/html') self.send_header('location','/restaurant') self.end_headers() return if self.path.endswith("/create/menuitem"): ctype,pdict = cgi.parse_header(self.headers.getheader('content-type')) if ctype == 'multipart/form-data': fields = cgi.parse_multipart(self.rfile,pdict) postcontent = fields.get('name') postcontent += fields.get('description') postcontent += fields.get('price') restid = re.compile('/restaurant/([0-9]+)/').match(self.path).group(1) rest = session.query(Restaurant).filter_by(id = restid).one() newitem = MenuItem(name = postcontent[0],description = postcontent[1],price = postcontent[2],restaurant = rest) session.add(newitem) session.commit() self.send_response(301) self.send_header('Content-type','text/html') self.send_header('location','/restaurant/%s' %(restid)) self.end_headers() return if self.path.endswith("/create/restaurant"): ctype,pdict = cgi.parse_header(self.headers.getheader('content-type')) if ctype == 'multipart/form-data': fields = cgi.parse_multipart(self.rfile,pdict) postcontent = fields.get('name') newrest = Restaurant(name = postcontent[0]) session.add(newrest) session.commit() self.send_response(301) self.send_header('content-type','text/html') self.send_header('location','/restaurant') self.end_headers() return if self.path.endswith("/register"): ctype,pdict = cgi.parse_header(self.headers.getheader('content-type')) if ctype == 'multipart/form-data': fields = cgi.parse_multipart(self.rfile,pdict) data = fields.get('username') data += fields.get('password') indb = session.query(User).filter_by(username = data[0]) if indb.count() == 1: self.send_response(302) self.send_header('content-type','text/html') self.send_header('error','Username already exists') self.send_header('location','/register') self.end_headers() return obj = User() obj.username = data[0] obj.password = data[1] session.add(obj) session.commit() self.send_response(302) self.send_header('content-type','text/html') self.send_header('location','/login') self.end_headers() return if self.path.endswith("/login"): ctype,pdict = cgi.parse_header(self.headers.getheader('content-type')) if ctype == 'multipart/form-data': fields = cgi.parse_multipart(self.rfile,pdict) data = fields.get('username') data += fields.get('password') user = session.query(User).filter_by(username = data[0]) if user.count() == 1: if user.one().password == data[1]: newsession = LoginSessions(user = user.one()) session.add(newsession) session.commit() c = Cookie.SimpleCookie() c['id'] = user.one().id self.send_response(301) self.send_header('content-type','text/html') self.send_header('Set-Cookie',c.output(header = '')) self.send_header('location','/restaurant') self.end_headers() return except IOError: self.send_response(404,"Input Data incorrect")
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import User, Catalog, Item, engine, Base Base.metadata.bind = engine # A DBSession() instance establishes all conversations with the database DBSession = sessionmaker(bind=engine) session = DBSession() # Create dummy user user1 = User(email='admin') user1.hash_password('123654') session.add(user1) session.commit() # Sample Catalogs Soccer = Catalog(name='Soccer') session.add(Soccer) Baseball = Catalog(name='Baseball') session.add(Baseball) Basketball = Catalog(name='Basketball') session.add(Basketball) Frisbee = Catalog(name='Frisbee') session.add(Frisbee) Snowboarding = Catalog(name='Snowboarding')
def get_user_by_email(self, email): """ Takes and email and checks the DB for the user,""" return User.get_by_email(dbs, email)
from database_setup import Restaurant, Base, MenuItem, User engine = create_engine('sqlite:///restaurantmenu.db') # Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents objects loaded into the # database session object. session = DBSession() # Create dummy user User1 = User(name="admin", email="*****@*****.**") session.add(User1) session.commit() # Menu for Michael Kitchen restaurant1 = Restaurant(name="=Michael's Kitchen", user_id="1") session.add(restaurant1) session.commit() menuItem1 = MenuItem(name="hot dogs", description="bun with hotdog" "served with ketchup your choice of condements.", price="$2.99", restaurant=restaurant1, user_id=1)
engine = create_engine('postgresql://*****:*****@localhost/catalog') Base.metadata.bind = engine # bind the session with the engine DBSession = sessionmaker(bind=engine) # create a new session session = DBSession() print("Session created!") # create a test user userDemo = User(id=5, name="Corvette Ray", email="*****@*****.**", picture='https://cars.usnews.com/static/images/Auto/izmo/i67064107/2019_chevrolet_corvette_angularfront.jpg') session.add(userDemo) session.commit() # create Categories and Items ''' #### Data for Demo Car Catalog#### ''' ''' #### SubCompact#### '''
#!/usr/bin/env python3 from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Category, Base, Item, User engine = create_engine('sqlite:///catalog.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # Create dummy user User1 = User(name="John Doe", email="*****@*****.**", picture='') session.add(User1) session.commit() # Create Categories category1 = Category(name="Soccer") session.add(category1) session.commit() category2 = Category(name="Basketball") session.add(category2) session.commit() category3 = Category(name="Baseball")
def new_user(): #print('at new user') if request.method == 'GET': state = ''.join(random.choice(string.ascii_uppercase + string.digits) \ for x in range(32)) login_session['state'] = state return render_template('newUser.html', STATE=state) #print(request.form) if request.method == 'POST': #Test for valid state token (unique session anti-forgery) #print('testing for valid state token') if request.form.get('state') != login_session.get('state'): response = make_response(json.dumps('Invalid state parameter'), 401) response.headers['Content-Type'] = 'application/json' return response name = request.form.get('name') username = request.form.get('username') password = request.form.get('password') conf_password = request.form.get('conf_password') security_question = request.form.get('security_question') security_question_answer = request.form.get('security_question_answer') conf_security_question_answer = request.form.get('conf_security_question_answer') pin = str(request.form.get('pin')) if pin != PIN: #print("incorrect PIN") # render intermediate screen msg = ["User registration is not possible.", "You are not authorized (incorrect PIN)."] return render_template('message.html', msg=msg, dest="/", my_time=8000) if (not username) or (not password): #print("missing arguments") # render intermediate screen msg = ["User registration is not possible.", "Missing arguments. It is necessary username and password."] return render_template('message.html', msg=msg, dest="/new_user", my_time=8000) #Check to see if password matches if password != conf_password: #print("password does not match") # render intermediate screen msg = ["User registration is not possible.", "Password confirmation does not match."] return render_template('message.html', msg=msg, dest="/new_user", my_time=8000) #Check to see if security question answer matches if (security_question_answer) and (security_question_answer != conf_security_question_answer): #print("security question answer does not match") # render intermediate screen msg = ["User registration is not possible.", "Security question answer confirmation does not match."] return render_template('message.html', msg=msg, dest="/new_user", my_time=8000) #Check if user with that username already exist id = -1 users = session.query(User).all() for user in users: decrypted_username = f.decrypt(user.username).decode() #print("username:"******"existing username") # render intermediate screen msg = ["User with username " + f.decrypt(user.username).decode() + " already exists.", "Registration is not possible."] return render_template('message.html', msg=msg, dest="/", my_time=8000) #Create new user #print("Requisites verified. Registering new user...") user = User(name=f.encrypt(name.encode()), username=f.encrypt(username.encode()), security_question=f.encrypt(security_question.encode())) user.hash_password(password) user.hash_passw_phrase_answer(security_question_answer) #print('username', f.decrypt(user.username).decode(), ' created') session.add(user) session.commit() # render intermediate screen msg = ["User " + f.decrypt(user.username).decode() + " successfully registered!", "Please, wait. Returning to the login page..."] return render_template('message.html', msg=msg, dest="/", my_time=8000)
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, Category, Item, User engine = create_engine('sqlite:///itemcatalog.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # Users user1 = User(name="Hamilcar Barca", email="*****@*****.**") session.add(user1) session.commit() user2 = User(name="Pyrrhus", email="*****@*****.**") session.add(user2) session.commit() # Category soccer category1 = Category(name="Soccer") session.add(category1) session.commit() item1 = Item(name="Football", description="very round and slippery", category=category1, user=user1) session.add(item1)
# Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create dummy user User1 = User(name="Rob Stark", email="*****@*****.**") session.add(User1) session.commit() # Create various category and item for testing purpose cat = Category(user_id=1, name="Soccer") session.add(cat) session.commit() equip = EquipmentItem(name="Ball", description="Standard Issue ball", category_id=1) session.add(equip) session.commit()
# Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() user1 = User(name="Hyomin Choi", email = "*****@*****.**") session.add(user1) session.commit() category1 = Category(name="Wet Food", user_id=1) session.add(category1) session.commit() category2 = Category(name="Treats", user_id=1 ) session.add(category2) session.commit() category3 = Category(name="Supplements",user_id=1)