Example #1
1
def app():
    app = Flask(__name__)
    app.debug = True
    api = Api(app)

    class User(object):
        def __init__(self, name):
            self.name = name

    class Hello(Resource):
        name = "name&required&default='world'"
        date_in = {"validater": "datetime", "input": True, "default": datetime.utcnow}
        date_out = "datetime&required&output"
        schema_inputs = {"get": {"name": name}, "get_user": {"name": name}, "post": {"date": date_in}}
        schema_outputs = {
            "get": {"hello": "unicode&required"},
            "get_user": {"user": {"name": name}},
            "post": {"date": date_out},
        }
        output_types = [User]

        def get(self, name):
            return {"hello": name}

        def get_user(self, name):
            return {"user": User(name)}

        def post(self, date):
            return {"date": date}

    api.add_resource(Hello)
    return app
Example #2
0
def config_api(app):
    api = Api(app, metafile="meta.json", docs=__doc__)
    app.route("/")(api.meta_view)
    auth = init_auth(api)
    auth.get_role(get_role)
    for x in ALL_RESOURCE:
        api.add_resource(x)
Example #3
0
def create_api():
    class Hello(Resource):
        schema_inputs = {
            "get": {"name": ("name&required&default='world'", "name")},
            "post_login": {"date": ("date&required", "date")},
        }
        hello = {"hello": "unicode&required"}
        schema_outputs = {
            "get": hello,
            "get_error": hello,
            "post_login": hello,
        }

        def get(self, name):
            return {"hello": name}

        def get_error(self):
            raise ValueError("get_error")

        def post_login(self, date):
            return {"hello": "world"}

    app = Flask(__name__)
    app.debug = True
    api = Api(app)
    api.add_resource(Hello)

    return api
Example #4
0
def config_api(app):
    api = Api(app, metafile="meta.json", docs=__doc__)
    app.route("/")(api.meta_view)
    auth = init_auth(api)
    auth.get_role(get_role)
    for x in ALL_RESOURCE:
        api.add_resource(x)
Example #5
0
def test_user_role():
    class Hello(Resource):

        def get(self):
            return "hello"

        def post_login(self):
            me = {"id": 123}
            return "login", 200, api.gen_auth_header(me)

    def user_role(uid, user):
        return "role_%s" % uid
    app = Flask(__name__)
    app.debug = True
    api = Api(app, fn_user_role=user_role)
    api.add_resource(Hello)

    with app.test_client() as c:
        rv = c.post("/hello/login")
        assert b"login" in rv.data
        assert api.auth_header in rv.headers
        auth = {api.auth_header: rv.headers[api.auth_header]}
        rv2 = c.get("/hello", headers=auth)
        assert str(g.me["id"]) == "123"
        # if permission file not exists, user_role will not be called
        # assert g.me["role"] == "role_123"
        assert g.me["role"] == None
Example #6
0
def test_parse_schema():
    hello = {"hello": "safestr&required"}
    sche_inputs = {
        "get": {"name": "name&default='world'"},
        "post_login": {
            "name": "name&default='world'",
            "password": "******"
        }
    }
    sche_outputs = {
        "get": hello,
        "post_login": hello
    }

    class Hello(Resource):

        schema_inputs = sche_inputs
        schema_outputs = sche_outputs
        output_types = [Flask]

        def get(self, name):
            pass

        def post_login(self, name, password):
            pass

    app = Flask(__name__)
    app.debug = True
    api = Api(app)
    api.add_resource(Hello)

    assert Hello.schema_inputs == validater.parse(sche_inputs)
    assert Hello.schema_outputs == validater.parse(sche_outputs)
    assert Hello.output_types == [Flask]
Example #7
0
def app(tmpdir):
    app = Flask(__name__)
    app.debug = True
    shutil.copy("tests/testdata/resource.json", str(tmpdir))
    shutil.copy("tests/testdata/permission.json", str(tmpdir))
    app.config["API_RESOURCE_JSON"] = join(str(tmpdir), "resource.json")
    app.config["API_PERMISSION_JSON"] = join(str(tmpdir), "permission.json")

    def fn_user_role(token):
        user_id = token["id"]
        user_roles = ["访客", "普通用户", "管理员"]
        return user_roles[user_id]

    api = Api(app)
    auth = Auth(api, fn_user_role=fn_user_role)

    class User(Resource):

        schema_inputs = {"post": {"id": "int(0,2)&required"}}

        def get(self):
            return "ok"

        def post(self, id):
            return "ok", auth.gen_header({"id": id})

    api.add_resource(User)
    api.add_resource(Permission, auth=auth)
    app.api = api
    app.auth = auth
    return app
Example #8
0
def create_app(tmpdir, refresh=True, cookie=None):
    class Hello:

        def get(self):
            """
            Get Name

            $output:
                name?str&optional: Your name
            """
            return {"name": g.token["name"]}

        def post(self, name):
            """
            Generate Token

            $input:
                name?str: Your name
            """
            if name == "admin":
                role = "admin"
            else:
                role = "normal"
            g.token = {"role": role, "name": name}
            return "OK"

    metafile = tmpdir.join("meta.json")
    json.dump({
        "$desc": "test",
        "$auth": {
            "refresh": refresh,
            "cookie": cookie
        },
        "$roles": {
            "admin": {
                "hello": ["get", "post"]
            },
            "guest": {
                "hello": ["post"]
            }
        }
    }, metafile.open("w"))

    app = Flask(__name__)
    app.secret_key = "secret_key"
    api = Api(app, metafile=metafile.strpath)

    auth = TokenAuth(api)

    @auth.get_role
    def get_role(token):
        if token:
            return token["role"]
        else:
            return "guest"

    api.add_resource(Hello)
    return app
Example #9
0
def create_app(tmpdir, refresh=True, cookie=None):
    class Hello:
        def get(self):
            """
            Get Name

            $output:
                name?str&optional: Your name
            """
            return {"name": g.token["name"]}

        def post(self, name):
            """
            Generate Token

            $input:
                name?str: Your name
            """
            if name == "admin":
                role = "admin"
            else:
                role = "normal"
            g.token = {"role": role, "name": name}
            return "OK"

    metafile = tmpdir.join("meta.json")
    json.dump(
        {
            "$desc": "test",
            "$auth": {
                "refresh": refresh,
                "cookie": cookie
            },
            "$roles": {
                "admin": {
                    "hello": ["get", "post"]
                },
                "guest": {
                    "hello": ["post"]
                }
            }
        }, metafile.open("w"))

    app = Flask(__name__)
    app.secret_key = "secret_key"
    api = Api(app, metafile=metafile.strpath)

    auth = TokenAuth(api)

    @auth.get_role
    def get_role(token):
        if token:
            return token["role"]
        else:
            return "guest"

    api.add_resource(Hello)
    return app
Example #10
0
def app():
    app = Flask(__name__)
    app.debug = True
    api = Api(app)

    class Hello(Resource):

        def get(self):
            return [123]

    api.add_resource(Hello)
    return app
Example #11
0
def test_gendocs_str():
    class Hello(Resource):
        """中文docstring for Hello哈哈"""

        def get(self):
            """你好啊"""
            return "hello"

    app = Flask(__name__)
    api = Api(app)
    api.add_resource(Hello)
    api.gen_resdocs()
    api.gen_resjs()
def test_gendocs():
    class Hello(Resource):
        """中文docstring for Hello哈哈"""

        def get(self):
            """你好啊"""
            return "hello"

    app = Flask(__name__)
    api = Api(app, docs=__doc__)
    api.add_resource(Hello)
    gen = Gen(api)
    gen.resjs('static/res.js')
    gen.resdocs('static/resdocs.html', resjs='static/res.js',
                bootstrap="bootstrap.css")
Example #13
0
def test_response_status_code():
    class Hello(Resource):

        def get(self):
            return 'hello world', 201

        def get_302(self):
            return redirect(url_for('hello'))

    app = Flask(__name__)
    app.debug = True
    api = Api(app)
    api.add_resource(Hello)
    with app.test_client() as c:
        assert c.get("/hello").status_code == 201
        assert c.get("/hello/302").status_code == 302
Example #14
0
def app():
    app = Flask(__name__)
    app.debug = True
    api = Api(app)

    class Hello(Resource):

        def get(self):
            return "hello"

        def get_error(self):
            raise ValueError("error")

    api.add_resource(Hello)
    app.resource = Hello
    app.api = api
    return app
Example #15
0
def test_parse_request():
    class Hello(Resource):

        def get(self):
            return "hello"

    app = Flask(__name__)
    app.debug = True
    bp = Blueprint("blueprint", __name__)
    api = Api(bp)
    api.add_resource(Hello)
    app.register_blueprint(bp, url_prefix="/api")
    with app.test_client() as c:
        rv = c.get("/api/hello")
        assert b"hello" in rv.data
        assert g.resource == "hello"
        assert g.action == "get"
        assert g.me["id"] is None
Example #16
0
def create_app(server_address, shared_folder):
    app = Flask(__name__, static_url_path="/static", static_folder="static/dist")
    if not exists(shared_folder):
        makedirs(shared_folder)
    app.add_url_rule('/shared/<filename>', 'shared', build_only=True)
    app.wsgi_app = SharedDataMiddleware(
        app.wsgi_app, {'/shared': shared_folder})
    bp_api = Blueprint("api", __name__)
    api = Api(bp_api)
    api.meta["$url_prefix"] = "/api"
    api.add_resource(Shared, server_address, shared_folder)
    app.register_blueprint(bp_api, url_prefix="/api")

    @app.route("/")
    def index():
        return app.send_static_file("index.html")

    return app
def app():
    app = Flask(__name__)
    app.debug = True
    api = Api(app)

    class User(object):

        def __init__(self, name):
            self.name = name

    class Hello(Resource):
        name = "name&required&default='world'"
        date_in = {'validater': 'datetime',
                   'input': True,
                   'default': datetime.utcnow}
        date_out = 'datetime&required&output'
        schema_inputs = {
            "get": {"name": name},
            "get_user": {"name": name},
            "get_list": {"name": name},
            "post": {"date": date_in}}
        schema_outputs = {
            "get": {"hello": "unicode&required"},
            "get_user": {"user": {"name": name}},
            "get_list": [{"name": name}],
            "post": {"date": date_out}
        }
        output_types = [User]

        def get(self, name):
            return {'hello': name}

        def get_user(self, name):
            return {'user': User(name)}

        def get_list(self, name):
            return [User(name)] * 5

        def post(self, date):
            return {'date': date}

    api.add_resource(Hello)
    return app
Example #18
0
def test_request_content_type():
    class Hello(Resource):
        schema_inputs = {
            "post": {"name": "safestr"}
        }

        def post(self, name):
            return {"hello": name}

    app = Flask(__name__)
    app.debug = True
    api = Api(app)
    api.add_resource(Hello)
    with app.test_client() as c:
        headers = {"Content-Type": "application/json"}
        params = dict(headers=headers, data='{"name": "jsoner"}')
        assert 200 == c.post("/hello", **params).status_code
        headers["Content-Type"] = "application/json;charset=UTF-8"
        assert 200 == c.post("/hello", **params).status_code
Example #19
0
def test_parse_request():
    class Hello(Resource):

        def get(self):
            return "hello"

    app = Flask(__name__)
    app.debug = True
    api = Api(app)
    api.add_resource(Hello)

    with app.test_request_context('hello'):
        assert request.endpoint == "hello"
        assert url_for("hello") == "/hello"
    with app.test_client() as c:
        rv = c.get("hello")
        assert 200 == rv.status_code
        assert b"hello" in rv.data
        assert g.resource == "hello"
        assert g.action == "get"
Example #20
0
def test_parse_request():
    class Hello(Resource):

        schema_inputs = {
            "post": {"name": "unicode&default='world'"},
            "put": "unicode&default='world'"
        }

        def get(self):
            return "hello"

        def post(self, name):
            return name

        def put(self, name):
            return "hello"

    app = Flask(__name__)
    app.debug = True
    api = Api(app)
    api.add_resource(Hello)

    with app.test_request_context('hello'):
        assert request.endpoint == "hello"
        assert url_for("hello") == "/hello"
    with app.test_client() as c:
        rv = c.get("hello")
        assert 200 == rv.status_code
        assert b"hello" in rv.data
        assert g.resource == "hello"
        assert g.action == "get"
    with app.test_client() as c:
        headers = {'Content-Type': 'application/json'}
        # empty request data is invalid json content
        assert c.post('hello', headers=headers).status_code == 400
        assert c.put('hello', headers=headers).status_code == 400
        assert c.post('hello', data="{}", headers=headers).status_code == 200
        assert c.put('hello', data="null", headers=headers).status_code == 200
        # bad json
        assert c.post('hello', headers=headers, data="x").status_code == 400
        assert c.put('hello', headers=headers, data="x").status_code == 400
Example #21
0
def test_blueprint():
    class Hello(Resource):

        def get(self):
            return "hello"

    app = Flask(__name__)
    app.debug = True
    bp = Blueprint("blueprint", __name__)
    api = Api(app, blueprint=bp)
    api.add_resource(Hello)
    app.register_blueprint(bp, url_prefix="/api")

    with app.test_request_context('/api/hello'):
        assert request.endpoint == "blueprint.hello"
        assert url_for("blueprint.hello") == "/api/hello"
    with app.test_client() as c:
        rv = c.get("/api/hello")
        assert 200 == rv.status_code
        assert b"hello" == rv.data
        assert g.resource == "hello"
        assert g.action == "get"
Example #22
0
def app():
    app = Flask(__name__)
    app.debug = True
    api = Api(app)

    class Hello(Resource):

        def get(self):
            return "hello"

        def get_error(self):
            raise ValueError("error")

        def post_login(self):
            return "login"

    api.add_resource(Hello)
    # name can't be unicode on py2
    api.add_resource(Hello, name=str("hi"))

    app.resource = Hello
    app.api = api
    return app
Example #23
0
def test_return_inner_custom_type():
    class User(object):

        def __init__(self, name):
            self.name = name

    class Hello(Resource):
        sche = {"name": "str"}
        schema_outputs = {
            "get": sche,
            "get_list": [sche],
            "get_dict": {"user": sche}
        }
        output_types = [User]

        def get(self):
            return User("kk")

        def get_list(self):
            return [User("kk")] * 10

        def get_dict(self):
            return {"user": User("kk")}
    app = Flask(__name__)
    app.debug = True
    api = Api(app)
    api.add_resource(Hello)
    with app.test_client() as c:
        assert 200 == c.get("/hello").status_code
        assert 200 == c.get("/hello/list").status_code
        assert 200 == c.get("/hello/dict").status_code
        user = loads(c.get("/hello").data)
        assert user == {"name": "kk"}
        userlist = loads(c.get("/hello/list").data)
        assert userlist == [{"name": "kk"}] * 10
        userdict = loads(c.get("/hello/dict").data)
        assert userdict["user"] == {"name": "kk"}
Example #24
0
def app():
    app = Flask(__name__)
    app.debug = True
    api = Api(app)

    class Hello(Resource):

        def get(self):
            return "hello"

        def get_error(self):
            raise ValueError("get_error")

        def post_login(self):
            return "login"

    @Hello.error_handler
    def error_handler(self, ex):
        return {"ok": "error_hander"}

    class File(Resource):

        def get(self):
            return "file"

        def get_error(self):
            raise ValueError("get_error")

        def post_login(self):
            return "login"

    api.add_resource(Hello)
    # name can't be unicode on py2
    api.add_resource(File, name=str("upload"))

    return app
Example #25
0
    def get_binary(self):
        def generate():
            rows = '0123456789'
            for i in range(1, 10):
                yield ','.join(rows[:i]) + '\n'

        return Response(generate(), mimetype='text/csv')

    def post_upload(self):
        files = request.files.getlist('upload')
        return {'recv': len(files)}

    def post_login(self, name):
        """
        $input:
            name@name: Your name
        """
        g.token = token = {'role': 'admin', 'name': name}
        return token

    def get_me(self):
        return g.token


api.add_resource(Test, api)
app.route('/')(api.meta_view)

if __name__ == '__main__':
    app.run(debug=True)
Example #26
0
from flask import Flask, Blueprint
from flask_restaction import Api
from flask_sqlalchemy import SQLAlchemy

from config import config

app = Flask(__name__)
app.config.from_object(config["development"])

# 数据库连接
db = SQLAlchemy(app)

# 蓝图
apiv1bp = Blueprint('api', __name__)
front = Blueprint('front', __name__)

# 过滤器

# view

# Flask-restAction 创建API,并且给API添加资源
apiv1 = Api(apiv1bp)
from app.apis.v1.demo import Hello
apiv1.add_resource(Hello)
apiv1.add_resource(type('Docs', (), {'get': apiv1.meta_view}))

# 蓝图添加路由
app.register_blueprint(front, url_prefix='/')
app.register_blueprint(apiv1bp, url_prefix='/v1')
# app.register_blueprint(apiv1bp, url_prefix='/v1')
        else:
            abort(404, "Not Found")

    def get_list(self):
        return [dict(v, id=k) for k, v in todos.items()]

    def post(self, **todo):
        if not todos:
            newid = 1
        else:
            newid = sorted(todos.keys())[-1] + 1
        todos[newid] = todo
        return dict(todo, id=newid)

    def put(self, id, **todo):
        if id in todos:
            todos[id] = todo
            return dict(todo, id=id)
        else:
            abort(404, "Not Found")

    def delete(self, id):
        if id in todos:
            del todos[id]

api.add_resource(Todo)
api.gen_resjs()

if __name__ == '__main__':
    app.run(debug=True)
Example #28
0
    """Hello world"""

    # 在 get 方法文档字符串中描述输入参数和输出的格式
    def get(self, name):
        """
        Get welcome message

        $input:
            name?str&default="world": Your name
        $output:
            message?str: Welcome message
        $error:
            400.InvalidData: 输入参数错误
            403.PermissionDeny: 权限不足
            501.xxx: xxx
            404.yyy: yyy
        """
        return Welcome(name)
        ##return "22"
        #return "400"
        #abort(404)
        #abort(404,Response())
        #abort(501, "error", "Server error")

# 添加资源
api.add_resource(Hello)
# 配置API文档的访问路径
app.route('/')(api.meta_view)

if __name__ == '__main__':
    app.run()
Example #29
0
from flask_restaction import Resource, Api, Gen

app = Flask(__name__)
api = Api(app)


class Hello(Resource):
    """hello world"""
    schema_inputs = {
        "get": {
            "name": ("safestr&default='world'", "your name")
        }
    }
    schema_outputs = {
        "get": {"hello": "unicode&required"}
    }

    def get(self, name):
        """welcome to flask-restaction"""
        return {"hello": name}

api.add_resource(Hello)

gen = Gen(api)
gen.resjs('static/res.js')
gen.resdocs('static/resdocs.html', resjs='/static/res.js',
            bootstrap='/static/bootstrap.min.css')

if __name__ == '__main__':
    app.run(debug=True)
Example #30
0
        $input:
            name?str: your name
        $output:
            welcome?str: welcome message
        """
        return {'welcome': name}


class User(Hello):
    """用户模块"""


class Article(Hello):
    """博客/文章"""


class World(Hello):
    """Hello World"""


api.add_resource(User)
api.add_resource(Hello)
api.add_resource(Article)
api.add_resource(World)
api.add_resource(type("Docs", (), {"get": api.meta_view}))


app.route('/')(api.meta_view)
if __name__ == '__main__':
    app.run()
Example #31
0
from __future__ import absolute_import
from flask import Flask
from flask_restaction import Api
from datetime import datetime
from validater import add_validater


def user_role(uid):
    if uid == 1:
        return "admin"


def iso_datetime_validater(v):
    if isinstance(v, datetime):
        return (True, v.isoformat())
    else:
        return (False, None)
add_validater("iso_datetime", iso_datetime_validater)

app = Flask(__name__)
app.debug = True
api = Api(app, fn_user_role=user_role)
app.config["JSON_AS_ASCII"] = False

from .users import User
from .todos import Todo
api.add_resource(User)
api.add_resource(Todo)
api.gen_resjs()
api.gen_resdocs()
Example #32
0
        abort(500)

    def get_binary(self):
        def generate():
            rows = '0123456789'
            for i in range(1, 10):
                yield ','.join(rows[:i]) + '\n'
        return Response(generate(), mimetype='text/csv')

    def post_upload(self):
        files = request.files.getlist('upload')
        return {'recv': len(files)}

    def post_login(self, name):
        """
        $input:
            name@name: Your name
        """
        g.token = token = {'role': 'admin', 'name': name}
        return token

    def get_me(self):
        return g.token


api.add_resource(Test, api)
app.route('/')(api.meta_view)

if __name__ == '__main__':
    app.run(debug=True)
Example #33
0
        print(name)
        user = User(name, password)
        return user.toDict()

    def put(self, user_id, name, password):
        user = filter(lambda x: True
                      if x._id == user_id else False, Userlist)[0]
        if name:
            user.name = name
        if password:
            user.password = password

        return user.toDict()

    def delete(self, user_id):
        global Userlist
        Userlist = filter(lambda x: False
                          if x._id == user_id else True, Userlist)
        return {"message": "OK"}


api.add_resource(Users)

gen = Gen(api)
gen.resjs('static/js/res.js')
gen.resdocs('static/resdocs.html',
            resjs='/static/js/res.js',
            bootstrap='/static/css/bootstrap.min.css')

if __name__ == '__main__':
    app.run(debug=True)
Example #34
0
        """
        Welcome to flask-restaction

        $input: "@name"
        $output: "@message"
        """
        return Welcome(name)

    def get_me(self):
        """
        Get welcome for me

        $output: "@message"
        """
        return Welcome(g.token["name"])

    def post(self, name):
        """Create auth headers

        $input: "@name"
        """
        g.token = {"name": name, "role": "normal"}
        return "OK"


api.add_resource(Hello, api)
api.add_resource(type('Docs', (), {'get': api.meta_view}))

if __name__ == '__main__':
    app.run(debug=True)
Example #35
0
        """
        Welcome to flask-restaction

        $input: "@name"
        $output: "@message"
        """
        return Welcome(name)

    def get_me(self):
        """
        Get welcome for me

        $output: "@message"
        """
        return Welcome(g.token["name"])

    def post(self, name):
        """Create auth headers

        $input: "@name"
        """
        g.token = {"name": name, "role": "normal"}
        return "OK"


api.add_resource(Hello, api)
api.add_resource(type('Docs', (), {'get': api.meta_view}))

if __name__ == '__main__':
    app.run(debug=True)
Example #36
0
        $input:
            name?str: your name
        $output:
            welcome?str: welcome message
        """
        return {'welcome': name}


class User(Hello):
    """用户模块"""


class Article(Hello):
    """博客/文章"""


class World(Hello):
    """Hello World"""


api.add_resource(User)
api.add_resource(Hello)
api.add_resource(Article)
api.add_resource(World)
api.add_resource(type("Docs", (), {"get": api.meta_view}))

app.route('/')(api.meta_view)
if __name__ == '__main__':
    app.run()