Exemplo n.º 1
0
def show(user_id):
    schema = UserSchema()
    user = User.get(id=user_id)

    if not user:
        abort(404)

    return schema.dumps(user)
Exemplo n.º 2
0
def get_user_endpoint(uid):

    # get user's checksum
    user = User.query.get(uid)
    # evaluate if matches given checksum
    if user is None:
        return jsonify(message=f'User {uid} does not exist!'), 404

    schema = UserSchema(only=('uid', 'name', 'avatar', 'title', 'identity',
                              'mnemonic', 'subscription', 'createdAt'))
    user = schema.dump(user)

    if user['identity'] == 0:  # artist
        releases = Media.query \
            .filter_by(uid=user['uid'], dist_type=False) \
            .order_by(Media.title) \
            .all()
        releases = MediaSchema(exclude=('uid', 'full_audio', 'demo_segment',
                                        'dist_type')).dump(releases, many=True)
        for release in releases:
            release['artist'] = user['name']
        user['releases'] = releases

        auctions = Auction.query \
            .filter_by(uid=user['uid']) \
            .order_by(Auction.start.desc()) \
            .all()
        auctions = AuctionSchema(only=('aid', 'assetId', 'amount', 'start',
                                       'end', 'sold', 'earnings', 'mid',
                                       'media.title',
                                       'media.cover')).dump(auctions,
                                                            many=True)
        for auction in auctions:
            auction['cover'] = auction['media']['cover']
            auction['title'] = auction['media']['title']
            auction['artist'] = user['name']
            del auction['media']
        user['auctions'] = auctions

    else:  # listener
        owns = Ownership.query.filter_by(uid=user['uid']).all()
        owns = OwnershipSchema(only=('aid', 'auction.assetId', 'auction.sold',
                                     'auction.earnings', 'mid', 'media.uid',
                                     'media.title',
                                     'media.cover')).dump(owns, many=True)
        for own in owns:
            own['assetId'] = own['auction']['assetId']
            own['sold'] = own['auction']['sold']
            own['earnings'] = own['auction']['earnings']
            own['title'] = own['media']['title']
            own['cover'] = own['media']['cover']
            own['artist'] = User.query.get(own['media']['uid']).name
            del own['auction']
            del own['media']
        user['owns'] = owns

    return jsonify(user), 200
Exemplo n.º 3
0
 def post(self):
     email = request.authorization.username
     password = request.authorization.password
     user = UserModel.query.filter(UserModel.user_email == email).filter(UserModel.user_pass == password).first()
     if user:
         user_schema = UserSchema()
         result = user_schema.dump(user)
         return jsonify(result.data)
     return {}, 404
Exemplo n.º 4
0
def show(user_id):
    # This will serialize our data
    schema = UserSchema()
    # This gets a user by ID
    user = User.get(id=user_id)

    # If we can't find a user, send a 404 response
    if not user:
        abort(404)

    # otherwise, send back the user data as JSON
    return schema.dumps(user)
Exemplo n.º 5
0
def register():
    schema = UserSchema()
    try:
        data = schema.load(request.get_json())
        user = User(**data)
        db.commit()
    except ValidationError as error:
        return jsonify({'error': error.messages}), 422

    return jsonify({
        'message': 'Registation successful',
        'token': user.generate_token()
    })
Exemplo n.º 6
0
def update(user_id):
    schema = UserSchema()
    user = User.get(id=user_id)

    if not user:
        abort(404)

    try:
        data = schema.load(request.get_json())
        user.set(**data)
        db.commit()
    except ValidationError as err:
        return jsonify({'message': 'Validation failed', 'errors': err.messages}), 422

    return schema.dumps(user)
Exemplo n.º 7
0
def create_user_endpoint():
    data = request.get_json()
    if data is None:
        return '', 400
    message = UserSchema().validate(data)
    if len(message) > 0:
        return jsonify(message), 400

    user = User(**data)
    db.session.add(user)
    db.session.commit()

    schema = UserSchema(only=('uid', 'name', 'avatar', 'identity',
                              'subscription', 'createdAt'))
    return jsonify(schema.dump(user)), 201
Exemplo n.º 8
0
def create():

    schema = UserSchema()

    try:

        data = schema.load(request.get_json())

        user = User(**data)

        db.commit()
    except ValidationError as err:

        return jsonify({'message': 'Validation failed', 'errors': err.messages}), 422

    return schema.dumps(user), 201
Exemplo n.º 9
0
def edit_profile():

    schema = UserSchema()
    data = request.get_json()
    if data.get('concession'):
        data['concession'] = data['concession'] == 'true'
    if data.get('keyword_ids'):
        print(g.current_user.keywords)
        previousKeywords = []
        for keyword in g.current_user.keywords:
            previousKeywords.append(keyword)
        data['keywords'] = [
            Keyword.get(id=keyword_id) for keyword_id in data['keyword_ids']
        ] + previousKeywords
        del data['keyword_ids']
    g.current_user.set(**data)
    db.commit()
    user_info = g.current_user
    return schema.dumps(user_info)
Exemplo n.º 10
0
def create():
    # This will deserialize the JSON from insomnia
    schema = UserSchema()

    try:
        # attempt to convert the JSON into a dict
        data = schema.load(request.get_json())
        # Use that to create a user object
        user = User(**data)
        # store it in the database
        db.commit()
    except ValidationError as err:
        # if the validation fails, send back a 422 response
        return jsonify({
            'message': 'Validation failed',
            'errors': err.messages
        }), 422

    # otherwise, send back the user data as JSON
    return schema.dumps(user), 201
Exemplo n.º 11
0
from pony.orm import db_session
from app import db
from models.Category import Category
from models.Listing import Listing
from models.User import User, UserSchema
from models.CartItem import CartItem

db.drop_all_tables(with_all_data=True)
db.create_tables()

with db_session():

    user_schema = UserSchema()

    user1 = User(username='******',
                 email='*****@*****.**',
                 password_hash=user_schema.generate_hash('pass'))

    user2 = User(username='******',
                 email='*****@*****.**',
                 password_hash=user_schema.generate_hash('pass'))

    user3 = User(username='******',
                 email='*****@*****.**',
                 password_hash=user_schema.generate_hash('pass'))

    user4 = User(username='******',
                 email='*****@*****.**',
                 password_hash=user_schema.generate_hash('pass'))

    user5 = User(username='******',
Exemplo n.º 12
0
def user_index():
    # This will serialize our data
    schema = UserSchema()  #many=True
    user = User.get(id=g.current_user.id)
    return schema.dumps(user)  # 'schema.dumps' converts the list to JSON
Exemplo n.º 13
0
def index():
    # This will serialize our data
    # `many=True` because there are many users, ie we expect a list
    schema = UserSchema(many=True)
    users = User.select()  # get all the users
    return schema.dumps(users)  # `schema.dumps` converts the list to JSON
Exemplo n.º 14
0
from pony.orm import db_session
from app import db
from models.Ad import Ad
from models.Medium import Medium
from models.Work import Work
from models.User import User, UserSchema
from datetime import datetime, timedelta

db.drop_all_tables(with_all_data=True)
db.create_tables()

with db_session():

    schema = UserSchema()
    animation = Medium(name='Animation')
    music = Medium(name='Music')
    application = Medium(name='Application')
    illustration = Medium(name='Illustration')

    Hiro = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pass'),
        lookingforwork=True,
        photo=
        "https://66.media.tumblr.com/73d02ec8972950c826286b1b131c52cd/tumblr_oxtpvh44kI1w3debko1_1280.png",
        bio=
        """Hiro Protganoist creates media artworks and mixed media artworks. By parodying mass media by exaggerating certain formal aspects inherent to our contemporary society, Protganoist makes works that can be seen as self-portraits. Sometimes they appear idiosyncratic and quirky, at other times, they seem typical by-products of American superabundance and marketing.

    His media artworks often refers to pop and mass culture. Using written and drawn symbols, a world where light-heartedness rules and where rules are undermined is created. By manipulating the viewer to create confusion, he touches various overlapping themes and strategies. Several reoccurring subject matter can be recognised, such as the relation with popular culture and media, working with repetition, provocation and the investigation of the process of expectations.
Exemplo n.º 15
0
def profile():
    schema = UserSchema()
    return schema.dumps(g.current_user)
Exemplo n.º 16
0
from flask_restful import Resource, abort, request
from models.PropertySupervisor import PropertySupervisor
from models.Comment import Comment, CommentSchema
from models.User import UserSchema
from common.Authentication import fetch_token

comment_schema = CommentSchema()
user_schema = UserSchema()


class SupervisorCommentsResource(Resource):
    def get(self, supervisor_id):
        # Authorize user.
        id, role = fetch_token(request.headers.get("Authorization"))
        if id is not None and not isinstance(id, int):
            abort(401, status="error", message=id)
        if id is None:
            abort(401,
                  status="error",
                  message="You have to log in to access this resource")
        supervisor = PropertySupervisor.query.filter_by(id=supervisor_id)\
            .first()
        if supervisor is None:
            abort(404,
                  message="Supervisor with id = {} doesn't exist".format(
                      supervisor_id))
        comments = Comment.query.filter_by(supervisor_id=supervisor.id).all()

        # Match every user id to the corresponding user name.
        comments_user = []
        for comment in comments:
Exemplo n.º 17
0
from pony.orm import db_session
from app import db
from models.Event import Event
from models.Format import Format
from models.User import User, UserSchema


db.drop_all_tables(with_all_data=True)
db.create_tables()

with db_session():
    schema = UserSchema()
    sensei = User(
        username='******',
        image='https://i.imgur.com/w7qm5UP.png',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pineapples')
    )


    five_a_side = Format(name='5-a-side')
    seven_a_side = Format(name='7-a-side')


    Event(
        name='Planet Futsal',
        image='https://i.imgur.com/jWd3gQb.jpg',
        venue='38 IBM Haruna St, Utako, Abuja',
        user=sensei,
        format=five_a_side,
        latitude=9.062720,
Exemplo n.º 18
0
from models.User import User, UserSchema
from flask import request, Response, jsonify
from flask_restful import Resource
from flask_jwt_extended import (create_access_token, set_access_cookies,
                                create_refresh_token, get_csrf_token,
                                set_refresh_cookies, jwt_required,
                                get_jwt_identity)
from helpers.api import custom_json_response
from helpers.database import save_to_database
from sqlalchemy import exc, or_
from helpers.distance import distance
from controllers.meal import create_meal, become_chef
import json

user_schema = UserSchema()
user_schema_private = UserSchema(
    exclude=['password', 'email', 'isChef', 'address'])


class ChefResource(Resource):
    def get(self, id=None):
        q_params = request.args
        if id:
            user = User.get_by_id(id)
            return user_schema_private.dump(user)

        applied_filters = []
        sql_filters = []

        if q_params.get("userCuisines"):
            chosen_cuisines = q_params.get("userCuisines").split(",")
Exemplo n.º 19
0
from flask import Blueprint, request, jsonify
from models.User import User, UserSchema
from marshmallow import ValidationError
from lib.secure_route import secure_route

user_schema = UserSchema()
users_schema = UserSchema(many=True)

api = Blueprint('users', __name__)


@api.route('/users/<int:id>', methods=['GET'])
def show(id):
    user = User.query.get(id)

    if not user:
        return jsonify({'message': 'Not found'}), 404

    return user_schema.jsonify(user)


@api.route('/users/<int:id>', methods=['PUT', 'PATCH'])
@secure_route
def update(id):

    user = User.query.get(id)

    if not user:
        return jsonify({'message': 'Not found'}), 404

    req_data = request.get_json()
Exemplo n.º 20
0
def retrieve_all_users():
    users = User.query.all()
    schema = UserSchema(exclude=('password', 'mnemonic'))
    return jsonify(*map(schema.dump, users)), 200
Exemplo n.º 21
0
 def get(self,user_id):
     user = UserModel.query.filter(UserModel.ID==user_id).first()
     user_schema = UserSchema()
     result = user_schema.dump(user)
     return jsonify(result.data)
Exemplo n.º 22
0
 def get(self):
     all_users = UserModel.query.all()
     user_schema = UserSchema(many=True)
     result = user_schema.dump(all_users)
     return jsonify(result.data)
Exemplo n.º 23
0
def index():
    schema = UserSchema(many=True)
    users = User.select()
    print(users)
    return schema.dumps(users)
Exemplo n.º 24
0
from pony.orm import db_session
from app import db
from models.User import User, UserSchema
from models.Landmark import Landmark
from models.Story import Story

# We delete all tables in our database
db.drop_all_tables(with_all_data=True)
db.create_tables() # We create tables in our database


with db_session():
    schema = UserSchema()
    alikurtulus = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('sda')
    )

    Story(
     cityname='Lisbon',
     title='Lisbon was great holiday',
     user=alikurtulus,
     description="Lisbon is, in my opinion, one of the best cities to spend a weekend and a perfect place to experience one of Europe’s smaller capitals – but don’t let the word ‘smaller’ fool you! Lisbon packs a hefty punch with great places to see, eat and places to totally ‘let your hair down’…",
     date='12.08.2018',
     image='https://handluggageonly.co.uk/wp-content/uploads/2015/09/DSC02292.jpg'
    )
    Story(
     cityname='Madrid',
     title='Madrid was dream holiday',
     user=alikurtulus,