コード例 #1
0
def endpoint_create(data: dict, user: str) -> dict:
    if "name" not in data or "country" not in data:
        return invalid_request

    name: str = data["name"]
    country: str = data["country"]

    if Profile.exists(user):
        return profile_already_exists

    Profile.create(user, name, country)

    return success
コード例 #2
0
def signup():
    if request.method == "POST":
        request_dict = request.get_json()
        response_dict = {}
        user_info = {}
        name = request_dict['name']
        for field in User.get_fields():
            if field == "id":
                continue
            if field == "password_hash":
                user_info['password'] = request_dict['password']
                continue
            if request_dict.get(field, None) != None:
                user_info[field] = request_dict[field]
        try:
            user = User.create(**user_info)
            # New profile info
            placeholder_info = {
                'name': name,
                'is_chef': False,
                "about_me": "Not entered",
                "profile_image": "No image uploaded",
                "favourite_recipe": "None yet,",
                "favourite_cuisine": "None yet,",
                "location": "Unknown Location"
            }
            profile = Profile.create(**placeholder_info)
            user.assign_one_to_one("profile", profile)
            # Since we're sending all the information back
            # to the front end, use the user_info dict as a
            # response dictionary
            user_info = user.to_dict(excludes=['profile', 'password_hash'])
            user_info['profile_id'] = user.profile.id
            email = user.email
            access_token = create_access_token(identity=email)
            refresh_token = create_refresh_token(identity=email)
            session['user_id'] = user.id
            # Put all information in a non nested dictionary
            # which will make it easier to get info in the frontend
            response_dict['status'] = 201
            response_dict['message'] = "Successfully created account!"
            response_dict['login'] = True
            response_dict['user'] = user_info
            response_dict['user']['profile'] = profile.to_dict(
                excludes=['user_id', 'recipes', 'user'])
            response = make_response(response_dict)
            response.set_cookie("user_id", str(user.id))
            # Set JWT cookies
            set_access_cookies(response, access_token)
            set_refresh_cookies(response, refresh_token)
            return response, 200
        except AssertionError as e:
            User.do_rollback()
            response_dict['status'] = 401
            response_dict['message'] = "%s" % (e)
            # Validation problem
            return jsonify(response_dict), 401
コード例 #3
0
ファイル: seed.py プロジェクト: hatchways/team-cheesesteak
def seed_database(debug=False):
    """
    WARNING: This will NOT create the tables for you if you
    dropped your entire database. You must re-create the database
    then run 'Base.metadata.create_all(<engine>)' to create your
    tables then you can run this without an issue!

    IMPORTANT: You need to import Base from models.models or else
    SQLAlchemy won't know about the models and therefore will NOT
    create the proper tables in your database which will cause this
    function to fail.

    Create data in the database by randomly generating values.
    Once this function is complete, it will write data that is
    likely to be used in testing to the 'seeded_objects_info.txt'
    file with separators and linebreaks to make it easier to read.

    When a user instance is created, its subsequent Profile is created
    as well and then they are associated with one another.
    After the user and profile objects are created, create some recipe
    objects to be associated with the profile object. Leave some profile
    objects without any recipes for filter testing.
    """
    if debug:
        # If something happened during object creation
        # we'll get a UNIQUE CONSTRAINT FAILED error
        # when trying again so, delete all the records
        # in the database and try to create the objects.
        # so we can preserve the existing tables
        from models.base_model import Base
        from db import engine
        for tbl in reversed(Base.metadata.sorted_tables):
            engine.execute(tbl.delete())

    # Create how ever many user and profile objects the user defined
    user_dicts = [
        {
            'street_address': "777 Brockton Avenue",
            'city': "Abington",
            "state_or_province": "Massachusetts",
            'country': "United States",
            'zip_code': "01001",
            'email': "*****@*****.**",
            'password': "******",
        },
        {
            'street_address': "30 Memorial Drive",
            'city': "Avon",
            'state_or_province': "Massachusetts",
            'country': "United States",
            'zip_code': "20194",
            'email': "*****@*****.**",
            'password': "******"
        },
        {
            'street_address': "250 Hartford Avenue",
            'city': "Toronto",
            'state_or_province': "Ontario",
            'country': "Canada",
            'zip_code': "A1A 1A1",
            'email': "*****@*****.**",
            'password': "******"
        },
    ]
    profile_dicts = [{
        'name': "Giuseppe",
        "is_chef": True,
        "about_me":
        "I love to cook and have been doing so for 15 years. My specialty is Italian food",
        "location": "Massachusettes, United States",
        'profile_image':
        "https://images.unsplash.com/photo-1600565193348-f74bd3c7ccdf?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80",
        'favourite_recipe':
        "Spicy Pork Tenderloin with Apples and Sweet Potatoes",
        'favourite_cuisine': "italian,",
    }, {
        'name': "Mario",
        "is_chef": False,
        'about_me':
        "I love food, if I could eat every hour of the day I would.",
        "location": "Massachusettes, United States",
        'profile_image':
        "https://images.unsplash.com/photo-1521341057461-6eb5f40b07ab?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80",
        'favourite_cuisine': "thai,",
    }, {
        'name': "Tessa",
        "is_chef": False,
        'about_me':
        "I'm not a chef but wish I was, I couldn't boil noodles without burning them!",
        "location": "Ontario, Canada",
        'profile_image':
        "https://images.unsplash.com/photo-1505999407077-7937810b98ae?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1188&q=80",
        'favourite_cuisine': "Mexican,"
    }]

    recipe_dicts = [
        {
            'name':
            'Spicy Pork Tenderloin with Apples and Sweet Potatoes',
            'description':
            "A spicy pork tenderloin with delicious green apples and sweet potatoes",
            'available':
            True,
            'cuisine':
            "french",
            'price':
            1000,
            'ingredients':
            "Pork Tenderloin,Green Apples,Sweet Potatoes,Rosemary",
            'required_items':
            "Dinner Plate, Kitchen Table, Oven",
            'image_urls':
            "https://images.unsplash.com/photo-1598514982205-f36b96d1e8d4?ixid=MXwxMjA3fDB8MHxzZWFyY2h8M3x8cG9yayUyMHRlbmRlcmxvaW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=60https://images.unsplash.com/photo-1598514982205-f36b96d1e8d4?ixid=MXwxMjA3fDB8MHxzZWFyY2h8M3x8cG9yayUyMHRlbmRlcmxvaW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=60,"
        },
        {
            'name':
            "Al's Burmese Chicken Curry",
            'description':
            "Chicken",
            'available':
            False,
            'cuisine':
            "indian",
            'price':
            1000,
            'ingredients':
            "Pork Tenderloin,Green Apples,Sweet Potatoes,Rosemary",
            'required_items':
            "Dinner Plate,Kitchen Table,Oven",
            'image_urls':
            "https://images.unsplash.com/photo-1501200291289-c5a76c232e5f?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxleHBsb3JlLWZlZWR8M3x8fGVufDB8fHw%3D&auto=format&fit=crop&w=1000&q=60,"
        },
        {
            'name':
            "Sweet Potato and Venison Shepherd's Pie",
            'description':
            "Shepherds Pie stuffed with sweet potatoes and venison, cooked to golden perfection",
            'available':
            True,
            'cuisine':
            "french",
            'price':
            2000,
            'ingredients':
            "Venison,Sweet potatoes,Gravy",
            'required_items':
            "Dinner Plate,Oven",
            'image_urls':
            "https://images.unsplash.com/photo-1600626336264-60ef2a55bd33?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NHx8c2hlcGhlcmRzJTIwcGllfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=60,"
        },
        {
            'name':
            "Gemelli Pasta with Roasted Pumpkin and Pancetta",
            "description":
            "Delicious pasta smothered in Pancetta with Roasted Pumpkin",
            'available':
            False,
            'cuisine':
            "italian",
            'price':
            1500,
            'ingredients':
            "Roasted Pumpkin,Pasta,Pancetta",
            'required_items':
            "Large Pot,Stove,Dinner Table",
            'image_urls':
            "https://images.unsplash.com/photo-1579631542720-3a87824fff86?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80,"
        },
        {
            'name':
            "Beef Stroganoff with Ground Beef",
            'description':
            "Beef stroganoff filled with ground beef, served with a delicious buttery dinner roll",
            'available':
            True,
            'cuisine':
            "turkish",
            'price':
            2500,
            'ingredients':
            "Ground Beef,Brown Gravy,Wide Egg Noodles,",
            'required_items':
            "Large Pot,Stove Top,Oven",
            'image_urls':
            "https://images.unsplash.com/photo-1504669221159-56caf7b07f57?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80,",
        },
    ]
    last_user = None
    for index in range(len(user_dicts)):
        print(index)
        new_user = User.create(**user_dicts[index])
        # Create profile
        new_profile = Profile()
        new_profile = new_profile.create(**profile_dicts[index])

        # Assign the new profile to the new user
        new_user.assign_one_to_one('profile', new_profile)

        # If we have another user, create messages between the
        # last one and the new one
        if last_user != None:
            new_conversation = Conversation.create(**{
                'user_one': last_user,
                'user_two': new_user
            })
            # Create messages for the two users
            last_users_message = Message.create(
                **{
                    'sender': last_user,
                    'content': "Hello %s how are you?" %
                    (new_user.profile.name)
                })
            new_users_message = Message.create(
                **{
                    'sender':
                    new_user,
                    'content':
                    "I'm good %s how about you?" % (last_user.profile.name)
                })
            # Add messages to the conversation
            new_conversation.add_to_relationship('messages',
                                                 last_users_message)
            new_conversation.add_to_relationship('messages', new_users_message)
            # Create 5 recipes for each user/profile
        new_recipe = Recipe.create(**recipe_dicts[index])
        # Add the new recipe to the One to Many field in the Profile model
        new_profile.add_to_relationship('recipes', new_recipe)
        last_user = new_user
    print_info(user_dicts, profile_dicts, recipe_dicts)