示例#1
0
def register_api(view, endpoint, url, pk='id', pk_type='string'):
    view_func = view.as_view(endpoint)
    app.add_url_rule(url,
                     defaults={pk: None},
                     view_func=view_func,
                     methods=[
                         'GET',
                     ])
    app.add_url_rule(url, view_func=view_func, methods=[
        'POST',
    ])
    app.add_url_rule('%s<%s:%s>' % (url, pk_type, pk),
                     view_func=view_func,
                     methods=['GET', 'PUT', 'DELETE'])
示例#2
0
def add_api(api_name, api_class, url, pk='id', pk_type='int'):
    view = api_class.as_view(api_name)
    app.add_url_rule(url,
                     defaults={'id': None},
                     view_func=view,
                     methods=[
                         'GET',
                     ])
    app.add_url_rule(url, view_func=view, methods=[
        'POST',
    ])
    app.add_url_rule('%s/<%s:%s>' % (url, pk_type, pk),
                     view_func=view,
                     methods=['GET', 'PUT', 'DELETE'])
示例#3
0
文件: repository.py 项目: booo/gid
        return jsonifiy({"status": "invalid data"})

    @requires_auth
    def delete(self, username, reponame):
        user = User.query.filter_by(username=username).first()
        repo = Repository.query.filter_by(name=reponame, owner=user).first()

        if repo != None and repo.owner.username == session["identity.name"]:

            shutil.rmtree(Repository._path(repo.owner.username, reponame))
            db.session.delete(repo)
            db.session.commit()

            return jsonify({"status": "success"})

        return jsonifiy({"status": "invalid data"})

    @staticmethod
    def _sanitize(value):
        import re

        return unicode(re.sub("[^\w]", "", value).strip())


app.add_url_rule("/api/repos", view_func=RepositoriesAPI.as_view("repos"), methods=["GET"])

app.add_url_rule("/api/repos/<username>", view_func=RepositoriesAPI.as_view("repos"), methods=["GET", "POST"])
app.add_url_rule(
    "/api/repos/<username>/<reponame>", view_func=RepositoriesAPI.as_view("repos"), methods=["GET", "PUT", "DELETE"]
)
示例#4
0
文件: session.py 项目: booo/gid
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()


        session['identity.name'] = auth.username
        return f(*args, **kwargs)
    return decorated


class SessionAPI(MethodView):

    @requires_auth
    def get(self):
        user = User.query.filter_by(username = session['identity.name']).first()
        form = ProfileForm(obj = user)

        return jsonify(form.toDict())


app.add_url_rule('/api/session',
                 view_func=SessionAPI.as_view('session'),
                 methods=['GET'])
示例#5
0
from graphene import Schema
from api.graphql.query.query import Query
from api.graphql.mutation.mutation import Mutation
from flask_graphql import GraphQLView
from api import app

schema = Schema(query=Query, mutation=Mutation, auto_camelcase=False)

app.add_url_rule('/graphql',
                 view_func=GraphQLView.as_view('graphql',
                                               schema=schema,
                                               graphiql=True))

# Optional, for adding batch query support (used in Apollo-Client)
#app.add_url_rule('/graphql/batch', view_func=GraphQLView.as_view('graphql', schema=schema, batch=True))
示例#6
0
import os

from flask import send_from_directory
from flask_restful import Api

from api import app
from api.controllers import index, BookListResource, AuthorListResource, BookResource, AuthorResource, LoginResource, \
    RefreshResource

app.add_url_rule('/', 'index', index)

api = Api(app)
api.add_resource(BookListResource, '/books', endpoint='book_list')
api.add_resource(BookResource, '/books/<int:id>', endpoint='book_object')
api.add_resource(AuthorListResource, '/authors', endpoint='author_list')
api.add_resource(AuthorResource, '/authors/<int:id>', endpoint='author_object')

api.add_resource(LoginResource, '/auth/login', endpoint='login')
api.add_resource(RefreshResource, '/auth/refresh', endpoint='refresh')

if app.config["DEBUG"]:
    app.add_url_rule(
        '/media/<path:filename>', 'media',
        lambda filename: send_from_directory(
            os.path.join(os.getcwd(), app.config["UPLOAD_FOLDER"]), filename))
示例#7
0
文件: user.py 项目: booo/gid
                                form.password.data)
                    db.session.add(user)
                    db.session.commit()

                    return jsonify(user=user.toDict())

                except IntegrityError as e:
                    return jsonify({"error": "Username or email do already exist"})


        return jsonify({"error": form.errors})


    @requires_auth
    def delete(self):
        raise NotYetImplemented()


app.add_url_rule('/api/users',\
                    view_func=UserAPI.as_view('users'),
                    methods=['GET','PUT','POST'])
app.add_url_rule('/api/users/<username>',\
                    view_func=UserAPI.as_view('users'),
                    methods=['GET', 'DELETE'])


@app.route('/api/users/new')
def userNewForm():
    form = RegistrationForm(request.form)
    return jsonify(form = form.toDict())
示例#8
0
        note = Note.query.filter(Note.user_id == user_id, Note.id == note_id).first()
        if not note:
            return {f"error": f"Notes with id {note_id} by user {user_id} not found"}, 404
        if note.user != user:
            return {f"error": f"Access denied to note with id={note_id}"}, 403
        for key in request.json:
            setattr(note, key, request.json[key])
        try:
            note.save()
            return jsonify(note.to_dict()), 200
        except:
            return jsonify({"error": f"All note params must be unique"}), 404

    @auth.login_required()
    def delete(self, user_id, note_id):
        user = g.user
        note = Note.query.filter(Note.user_id == user_id, Note.id == note_id).first()
        if not note:
            return {f"error": f"Notes with id {note_id} by user {user_id} not found"}, 404
        if note.user != user:
            return {f"error": f"Access denied to note with id={note_id}"}, 403
        note.delete()
        return jsonify({f"Note with id {note_id}": "deleted"}), 200


app.add_url_rule('/notes', view_func=NotesAllView.as_view('notes_create'), methods=['GET', ])
app.add_url_rule('/users/<int:user_id>/notes', view_func=NoteView.as_view('note_operation'),
                 methods=["GET", "POST"])
app.add_url_rule('/users/<int:user_id>/notes/<int:note_id>', view_func=NoteUserView.as_view('note_operation1'),
                 methods=["GET", "PUT", "DELETE"])
示例#9
0
        True
        >>> validate('52998224725')
        True
        >>> validate('529 982 247 25')
        True
        >>> validate('abc.11f.11c-1g')
        False
        >>> validate('')
        False
        """

        # Verifica a formatação do CPF
        cpf = ''.join(re.findall(r'\d', str(cpf)))

        # Verifica se o CPF possui 11 números:
        if (not cpf or len(cpf) < 11):
            return {"is_valid": False}

        return {"is_valid": True}

    def post(self):
        data = request.get_json()
        cpf = data.get('cpf')
        if cpf is None:
            return abort(401, 'chave não encontrada: cpf')
        return jsonify(self.validar_cpf(cpf))


cpf_view = CpfView.as_view('cpf_view')
app.add_url_rule('/cpf/', view_func=cpf_view, methods=['POST'])
示例#10
0
    def delete(self, user_id):
        user = User.query.get(user_id)
        if not user:
            return {f"error": f"Note with id {user_id} not found"}, 404
        user.delete()
        return jsonify({f"Note with id {user_id}": "deleted"}), 200


class UserAllView(MethodView):

    def get(self):
        users = User.query.all()
        if not users:
            return {f"error": "Users not found"}, 404
        return jsonify([user.to_dict() for user in users])

    @validate("json", USER_CREATE)
    def post(self):
        user = User(**request.json)
        user.set_password(request.json["password"])
        try:
            user.save()
            return jsonify(user.to_dict()), 201
        except:
            return jsonify({"error": "User params must be unique"})


app.add_url_rule('/users/<int:user_id>', view_func=UserView.as_view('user_operation'), methods=["GET", "PUT", "DELETE"])
app.add_url_rule('/users', view_func=UserAllView.as_view('user_create'), methods=['GET', "POST"])