コード例 #1
0
def createUser(login_session):
    newUser = User(name=login_session['username'],
                   email=login_session['email'],
                   picture=login_session['picture'])
    session.add(newUser)
    session.commit()
    user = session.query(User).filter_by(email=login_session['email']).one()
    return user.id
コード例 #2
0
def createUser(login_session):
    """
    Create a local user account
    :param login_session:
    :return: user.id
    """
    NewUser = User(name=login_session['username'],
                   email=login_session['email'],
                   picture=login_session['picture'])
    session.add(NewUser)
    session.commit()
    user = session.query(User).filter_by(email=login_session['email']).one()
    return user.id
コード例 #3
0
def new_user(user_session):
    """Generate new user based on session

    Args:
        user_session: session containing user data

    Returns:
        id of user
    """
    user = User(name=user_session['username'], email=user_session['email'])
    session.add(user)
    session.flush()
    session.commit()
    return user.id
コード例 #4
0
# "http://randomuser.me/api/?nat=ca,us&noinfo&exc=login,cell,id&results=15"

# 3. Get json object from response
json_obj = response.json()

# 4. Create User(s)
for item in json_obj["results"]:

    user = User(item["name"]["first"],
                item["name"]["last"],
                item["email"],
                item["gender"][0].upper(),
                item["dob"].split(" ", 1)[0],  # trim to keep date only
                item["phone"],
                item["location"]["street"],
                item["location"]["city"],
                item["location"]["state"],
                item["nat"],
                item["location"]["postcode"],
                item["registered"].split(" ", 1)[0],  # trim to keep date only
                random.randint(1, types_num),
                item["picture"]["large"],
                "system")
    # Add User to session, one at a time
    session.add(user)

# 5. Commit session, insert all Users and display message
session.commit()
print("Added " + quantity + " users!")

コード例 #5
0
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from setup_database import Base, User, Expedition, Category, Item, expeditions_categories


engine = create_engine('sqlite:///catalog.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()


u = User(name='Robo Hiker',
         email='*****@*****.**',
         picture='http://cdn.phys.org/newman/csz/news/800/2013/walkingrobot.jpg')


e = Expedition(title='Gros Mourne', description='''Gros Morne National Park is a world heritage site located on the west coast of Newfoundland. At 1,805 km2 (697 sq mi), it is the second largest national park in Atlantic Canada; it is surpassed by Torngat Mountains National Park, which is 9,700 km2 (3,700 sq mi). The park takes its name from Newfoundland's second-highest mountain peak (at 2,644 ft/806 m) located within the park.
Its French meaning is "large mountain standing alone," or more literally "great sombre." Gros Morne is a member of the Long Range Mountains, an outlying range of the Appalachian Mountains, stretching the length of the island's west coast. It is the eroded remnants of a mountain range formed 1.2 billion years ago. "The park provides a rare example of the process of continental drift, where deep ocean crust and the rocks of the earth's mantle lie exposed."[1]
The Gros Morne National Park Reserve was established in 1973, and was made a national park in October 1, 2005.''')

c = Category(name="Climbing",
             description="The step cliff of Western Brook Pond are up to 600 m (2000 ft) high and offer plenty of challenges for climbers",
             picture="img/climbing_bck.jpg",
             user_id=1)



e = session.query(Expedition).first()
c = session.query(Category).filter_by(name='Climbing').one()
e.category.append(c)
コード例 #6
0
version10 = GameVersion(name="2.5")
session.add(version10)
session.commit()

version11 = GameVersion(name="2.6")
session.add(version11)
session.commit()

version12 = GameVersion(name="3.0")
session.add(version12)
session.commit()

user1 = User(
    name="David Brewer",
    email="*****@*****.**",
    picture=
    "https://lh4.googleusercontent.com/-YgQaZfQ_l28/AAAAAAAAAAI/AAAAAAAAABw/43vQlNZ2-Uw/photo.jpg"
)
session.add(user1)
session.commit()

build1 = Build(
    title=
    "Sarang's Endgame TS/LA/Barrage Archer | Pathfinder | Crit Bow | Videos | Budget Version",
    author="_Saranghaeyo_",
    character_class_name="Ranger",
    short_description="Fun lightning bow build ",
    long_description="""Hello everyone, I'm _Saranghaeyo_.

This is my Endgame TS/LA/Barrage Archer. I've been playing since Torment League (Patch 1.3) where I started as a Tornado Shot/Puncture Ranger and I've loved the build ever since. Since then I've put countless hours into Bow Attack builds with various classes and gear sets over Standard and many challenge leagues. It is my favorite character archetype in Path of Exile.
コード例 #7
0
import datetime

from setup_database import Base, Category, Item, User
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///catalog.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()

dumby_user = User(name="John Doe", email="*****@*****.**")

# populate initial categories
fruit_category = Category(name="Fruit")
session.add(fruit_category)

vegetables_category = Category(name="Vegetables")
session.add(vegetables_category)

protein_category = Category(name="Proteins")
session.add(protein_category)

grains_category = Category(name="Grains")
session.add(grains_category)

# populate initial items for each category
apple = Item(name="Apple",
             description="An apple is a sweet, " +
             "edible fruit produced by an apple tree.",
             category=fruit_category,
コード例 #8
0
def login():
    # Validate state token
    if request.args.get('state') != login_session['state']:
        flash('Sorry, we couldn\'t log you in. Error Code 1')
        return '1'
    # Obtain authorization code
    code = request.data
    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(code)
    except FlowExchangeError:
        flash('Sorry, we couldn\'t log you in. Error Code 2')
        return '2'

    # Check that the access token is valid.
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v2/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:
        flash('Sorry, we couldn\'t log you in. %s' %
              json.dumps(result.get('error')))
        return '10'

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        flash('Sorry, we couldn\'t log you in. Error Code 3')
        return '3'

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        flash('Sorry, we couldn\'t log you in. Error Code 4')
        return '4'

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        flash('You\'re already logged in')
        return '11'

    # Store the access token in the session for later use.
    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    # Get user info
    userinfo_url = 'https://www.googleapis.com/oauth2/v2/userinfo'
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()
    login_session['email'] = data['email']

    user = session.query(User).filter_by(email=data['email']).first()
    if user is None:
        session.add(User(email=data['email'], admin=False))
        session.commit()

    flash('You are now logged in as %s' % data['name'])

    return data['email']
コード例 #9
0
def add_user():
    """ GET: Display Add User page
        POST: Add New User and redirect to newly added User Details page """

    if request.method == 'GET':
        user_types = session.query(Type)

    elif request.method == 'POST':

        user_types = session.query(Type)

        # If not signed in, set appropriate message
        # and render Add User page
        if 'username' not in login_session:
            setAlert('warning', 'You must be signed in to add new user')
            return render_template("add-user.html",
                                   user_types=user_types,
                                   login_session=login_session,
                                   alert=getAlert())

        # Get today's date as registration date
        now = datetime.datetime.now()
        register_date = "{0}-{1}-{2}".format(str(now.year),
                                             str(now.month), str(now.day))

        # Set user avatars depending on gender
        if request.form["gender"].upper() == "M":
            profile_avatar = "/static/avatar_male.png"
        else:
            profile_avatar = "/static/avatar_female.png"

        user = User(request.form["firstNameInput"],
                    request.form["lastNameInput"],
                    request.form["emailInput"],
                    request.form["gender"].upper(),
                    request.form["datepicker"],
                    request.form["phoneInput"],
                    request.form["addressInput"],
                    request.form["cityInput"],
                    request.form["stateInput"],
                    request.form["countryInput"],
                    request.form["postInput"],
                    register_date,
                    request.form["userTypeSelect"],
                    profile_avatar,  # picture
                    login_session['email'])

        try:
            session.add(user)
            session.commit()

            # Get newly create user's info
            user = session.query(User).order_by(User.id.desc()).first()
            setAlert('success', 'Added new user ' +
                     user.first_name + ' ' + user.last_name)

            return redirect(url_for('user_details', user_id=user.id))

        except (Exception) as error:
            print("Error while adding new user.")
            setAlert('danger', 'Error while adding new user')
            return render_template("add-user.html",
                                   user_types=user_types,
                                   login_session=login_session,
                                   alert=getAlert())

    return render_template("add-user.html",
                           user_types=user_types,
                           login_session=login_session)