frol / flask-restplus-server-example Goto Github PK
View Code? Open in Web Editor NEWReal-life RESTful server example on Flask-RESTplus
Home Page: http://flask-restplus-example-server.herokuapp.com/api/v1/
License: MIT License
Real-life RESTful server example on Flask-RESTplus
Home Page: http://flask-restplus-example-server.herokuapp.com/api/v1/
License: MIT License
It seems that commonpath module is not supported in some python versions.
I'm using Python 2.7.6 and it's not supported.
Instead, I used not os.path.commonprefix.
(I am actually trying to implement it in my project, will release PR if I succeed and got the time)
I would like to add multiple parameters to an endpoint, essentially chaining them as so:
@api.parameters(SomeParameters())
@api.parameters(MoreParameters())
@api.parameters(EvenMoreParameters())
def get(self, args):
...
However, this results in a separate dict for each set of parameters and does not concatenate the arguments as I had expected. Also, Swagger does not seem to parse all of the argument options as only the topmost decorator appears in the docs.
I could simply create another Parameters class that combines all of the fields from the others, but I'd like to avoid having to create one for each desired combination of parameters.
Another idea I had was to create a method that would accept any number of Parameter objects and return a new dynamic Schema object with all of the combined fields. Something like:
@api.parameters(many_params(SomeParameters(), MoreParameters(), EvenMoreParameters()))
def get(self, args):
...
What is the recommended approach to accomplish this? I feel like I must be missing an easier way...
Hi,
I have cloned the repository and trying to run the project. I am using command invoke app.run
. All dependencies are installing successfully. Migrations are running good. I have checked the db and all tables are created. However i am getting error:
C:\Users\Administrator\AppData\Local\Programs\Python\Python35\Scripts\invoke
[Errorno 2] No Such File or Directory.
I have checked that invoke.py
is present in above mentioned path.
Any workaround for this problem? I am running it on windows 7 64 bit with python 3.5.2
The changes are quite radical, so it will take some time to get things going.
Just for the reference: noirbizarre/flask-restplus#267
Implement Parameters.Meta.required
support as a proof of concept of marshmallow-code/marshmallow#344.
Currently, we already have the assumption in the code, that the Parameters.Meta.required
works as expected, but it doesn't (there wasn't such support ever, I just mocked it).
Hey,
Thanks again but I'm running into further issues:
>> FLASK_CONFIG=development invoke app.run [flask_restplus_example]ilaif@Ilai
Traceback (most recent call last):
File "/Users/ilaif/.virtualenvs/flask_restplus_example/bin/inv", line 11, in <module>
sys.exit(program.run())
File "/Users/ilaif/.virtualenvs/flask_restplus_example/lib/python2.7/site-packages/invoke/program.py", line 269, in run
self._parse(argv)
File "/Users/ilaif/.virtualenvs/flask_restplus_example/lib/python2.7/site-packages/invoke/program.py", line 327, in _parse
self.parse_tasks()
File "/Users/ilaif/.virtualenvs/flask_restplus_example/lib/python2.7/site-packages/invoke/program.py", line 488, in parse_tasks
self.parser = Parser(contexts=self.collection.to_contexts())
File "/Users/ilaif/.virtualenvs/flask_restplus_example/lib/python2.7/site-packages/invoke/collection.py", line 325, in to_contexts
name=primary, aliases=aliases, args=task.get_arguments()
File "/Users/ilaif/.virtualenvs/flask_restplus_example/lib/python2.7/site-packages/invoke/tasks.py", line 193, in get_arguments
arg_names, spec_dict = self.argspec(self.body)
File "/Users/ilaif/Desktop/flask-restplus-server-example/tasks/app/_utils.py", line 26, in argspec
return super(Task, self).argspec(body)
File "/Users/ilaif/.virtualenvs/flask_restplus_example/lib/python2.7/site-packages/invoke/tasks.py", line 143, in argspec
context_arg = arg_names.pop(0)
IndexError: pop from empty list
Any thoughts?
It is reported that locations=('json', 'files')
in @Namespace.parameters
decorator breaks Swagger config:
@api.parameters(
parameters.CreateTeamParameters(),
locations=('json', 'files')
)
def post(self, ...):
...
The Swagger config results in:
"schema": {
"properties": {
"source_file": {
"type": "file"
},
...
},
"type": "object"
}
Instead of
"parameters": [
{
"in": "formData",
"name": "source_file",
"required": false,
"type": "file"
},
...
]
This might be related to #20.
/cc @DurandA
Relevant article: http://zacstewart.com/2012/04/14/http-options-method.html
BTW, by "available methods" I also assume permissions check, so clients can check which action elements should be hidden/disabled.
This is the application
flow type in OpenAPI (Swagger) Specification.
Currently, schema (model) is required for all non-error HTTP codes. There is no need to bother with models when HTTP/204 (No content) is going to be responded, so no model might be valid option in the Namespace.response
decorator.
I would try to implement it as missing model, something along these lines, but you will need to change the latter code do expect None model:
- if model is None:
+ if model is None and code != 204:
As a subtask, it would be nice to find a place where HTTP/204 code is defined as constant (Flask or Werkzeug might have it).
/cc @khorolets
invoke app.run --no-install-dependencies
or invoke app.dependencies.install_swagger_ui
works fine.
invoke app.dependencies.install
fails with error.
2017-03-07 17:21:01,359 [INFO] [tasks.app.dependencies] Installing project dependencies...
Traceback (most recent call last):
File "/Users/dog/.virtualenvs/flask_restplus_env/bin/invoke", line 11, in <module>
sys.exit(program.run())
File "/Users/dog/.virtualenvs/flask_restplus_env/lib/python2.7/site-packages/invoke/program.py", line 270, in run
self.execute()
File "/Users/dog/.virtualenvs/flask_restplus_env/lib/python2.7/site-packages/invoke/program.py", line 381, in execute
executor.execute(*self.tasks)
File "/Users/dog/.virtualenvs/flask_restplus_env/lib/python2.7/site-packages/invoke/executor.py", line 113, in execute
result = call.task(*args, **call.kwargs)
File "/Users/dog/.virtualenvs/flask_restplus_env/lib/python2.7/site-packages/invoke/tasks.py", line 111, in __call__
result = self.body(*args, **kwargs)
File "/Users/dog/projects/forks/flask-restplus-server-example/tasks/app/run.py", line 37, in run
context.invoke_execute(context, 'app.dependencies.install')
File "/Users/dog/projects/forks/flask-restplus-server-example/tasks/__init__.py", line 73, in invoke_execute
results = Executor(namespace, config=context.config).execute((command_name, kwargs))
File "/Users/dog/.virtualenvs/flask_restplus_env/lib/python2.7/site-packages/invoke/executor.py", line 113, in execute
result = call.task(*args, **call.kwargs)
File "/Users/dog/.virtualenvs/flask_restplus_env/lib/python2.7/site-packages/invoke/tasks.py", line 111, in __call__
result = self.body(*args, **kwargs)
File "/Users/dog/projects/forks/flask-restplus-server-example/tasks/app/dependencies.py", line 102, in install
install_python_dependencies(context)
File "/Users/dog/.virtualenvs/flask_restplus_env/lib/python2.7/site-packages/invoke/tasks.py", line 111, in __call__
result = self.body(*args, **kwargs)
File "/Users/dog/projects/forks/flask-restplus-server-example/tasks/app/dependencies.py", line 27, in install_python_dependencies
context.run("pip install -r requirements.txt %s" % ('--upgrade' if force else ''))
File "/Users/dog/.virtualenvs/flask_restplus_env/lib/python2.7/site-packages/invoke/context.py", line 53, in run
return runner_class(context=self).run(command, **kwargs)
File "/Users/dog/.virtualenvs/flask_restplus_env/lib/python2.7/site-packages/invoke/runners.py", line 261, in run
self.encoding = opts['encoding'] or self.default_encoding()
File "/Users/dog/.virtualenvs/flask_restplus_env/lib/python2.7/site-packages/invoke/runners.py", line 842, in default_encoding
default = locale.getdefaultlocale()[1]
File "/Users/dog/.virtualenvs/flask_restplus_env/lib/python2.7/locale.py", line 543, in getdefaultlocale
return _parse_localename(localename)
File "/Users/dog/.virtualenvs/flask_restplus_env/lib/python2.7/locale.py", line 475, in _parse_localename
raise ValueError, 'unknown locale: %s' % localename
ValueError: unknown locale: UTF-8
@frol Can you propose the place where to start finding the reason? I was looking on the line 27 but didn't see anything to produce the error.
Hey,
Sounds like a great project. However I'm trying to run it on my local machine (OSX El-Capitan, Python 2.7.10) and I receive an error:
>> invoke app.run
2016-11-18 12:15:27,067 [WARNING] [tasks.app.db] Alembic cannot be imported, so some app.db.* tasks won't be available!
Traceback (most recent call last):
File "/usr/local/bin/invoke", line 11, in <module>
sys.exit(program.run())
File "/usr/local/lib/python2.7/site-packages/invoke/program.py", line 269, in run
self._parse(argv)
File "/usr/local/lib/python2.7/site-packages/invoke/program.py", line 325, in _parse
self.load_collection()
File "/usr/local/lib/python2.7/site-packages/invoke/program.py", line 473, in load_collection
coll = loader.load(coll_name) if coll_name else loader.load()
File "/usr/local/lib/python2.7/site-packages/invoke/loader.py", line 53, in load
module = imp.load_module(name, fd, path, desc)
File "/Users/ilaif/Desktop/flask-restplus-server-example/tasks/__init__.py", line 61, in <module>
from . import app
File "/Users/ilaif/Desktop/flask-restplus-server-example/tasks/app/__init__.py", line 8, in <module>
from . import dependencies, env, db, run, users
File "/Users/ilaif/Desktop/flask-restplus-server-example/tasks/app/db.py", line 272, in <module>
def init_development_data(context, upgrade_db=True, skip_on_failure=False):
File "/Users/ilaif/Desktop/flask-restplus-server-example/tasks/app/_utils.py", line 58, in app_context_task
return Task(wrapper, **kwargs)
File "/usr/local/lib/python2.7/site-packages/invoke/tasks.py", line 58, in __init__
self.positional = self.fill_implicit_positionals(positional)
File "/usr/local/lib/python2.7/site-packages/invoke/tasks.py", line 149, in fill_implicit_positionals
args, spec_dict = self.argspec(self.body)
File "/Users/ilaif/Desktop/flask-restplus-server-example/tasks/app/_utils.py", line 21, in argspec
return super(Task, self).argspec(body)
File "/usr/local/lib/python2.7/site-packages/invoke/tasks.py", line 144, in argspec
raise TypeError("Tasks must have an initial Context argument!")
TypeError: Tasks must have an initial Context argument!
I must be missing something very trivial, I event tried to manually pip install the requirements to make sure I have all the dependencies.
Thanks,
Ilai.
I would expect to return a lazy queryset from the resource method handler, and some smart (explicit) magic will take care of OpenAPI/Swagger documentation, offsetting and limiting the data, and setting X-Total-Count
header to the response.
There are a few solutions I have in mind, but none of them is perfect to me:
Wrap the @api.response()
decorator, so we have the input parameters available, the original response, and the control over serialization:
@api.route('/my_resources/')
class MyResources(Resource):
@parameters.MyParametersInheritedFromPaginationParameters().paginate(
api.response(schemas.MySchema)
)
def get(self, args):
return models.MyResource.query.all()
or
@api.route('/my_resources/')
class MyResources(Resource):
@api.parameters(parameters.MyParametersInheritedFromPaginationParameters())
@api.paginate(
api.response(schemas.MySchema)
)
def get(self, args):
return models.MyResource.query.all()
Extend the @api.response
decorator to have hooks before the object gets dumped with a schema (so we can limit and offset the queryset), and after the Response is generated (so we can inject the header)
References:
P.S. To document the headers
in Swagger.json, we need the latest master of flask-restplus (the latest 0.10.1 release doesn't include the fix for noirbizarre/flask-restplus#119).
On centos 6 and python 3.4 when executing invoke app.run following error occurs
2017-01-11 13:04:17,614 [INFO] [tasks.app.dependencies] Project dependencies are installed. 2017-01-11 13:04:17,615 [INFO] [tasks.app.dependencies] Installing Swagger UI assets... 2017-01-11 13:04:17,616 [INFO] [tasks.app.dependencies] Downloading Swagger UI assets... 2017-01-11 13:04:17,909 [INFO] [tasks.app.dependencies] Unpacking Swagger UI assets... 2017-01-11 13:04:18,069 [INFO] [tasks.app.dependencies] Swagger UI is installed. Traceback (most recent call last): File "/usr/bin/invoke", line 11, in <module> sys.exit(program.run()) File "/usr/lib/python3.4/site-packages/invoke/program.py", line 274, in run self.execute() File "/usr/lib/python3.4/site-packages/invoke/program.py", line 389, in execute executor.execute(*self.tasks) File "/usr/lib/python3.4/site-packages/invoke/executor.py", line 113, in execute result = call.task(*args, **call.kwargs) File "/usr/lib/python3.4/site-packages/invoke/tasks.py", line 111, in __call__ result = self.body(*args, **kwargs) File "/root/flask-restplus-server-example-master/tasks/app/run.py", line 40, in run app = create_app() File "/root/flask-restplus-server-example-master/app/__init__.py", line 62, in create_app from . import extensions File "/root/flask-restplus-server-example-master/app/extensions/__init__.py", line 15, in <module> from sqlalchemy_utils import force_auto_coercion, force_instant_defaults ImportError: cannot import name 'force_auto_coercion'
Is there a reason why requirements.txt
does not include -r tests/requirements.txt
?
When using api.parameters decorator, the locations parameter is not taken into account to generate the documentation (@api.parameters(parameters.MyParameters(many=False), locations=('json',) )
.
My current workaround is to use the namespace.expect decorator with a flask_restplus model but it is not very consistent.
I would happily submit a pull request if someone point me in the right direction on how to add this.
For example I have models like this :
# modules/patients/models.py
class Patient(db.Model, OwnerMixin):
__owner_backref_name__ = "patients"
id = db.Column(db.Integer, primary_key=True)
phone = db.Column(db.String)
email = db.Column(db.String)
first_name = db.Column(db.String)
last_name = db.Column(db.String)
birthday = db.Column(db.DateTime)
zip_code = db.Column(db.String)
address = db.Column(db.String)
# I would like to do this, but there's circular import....
@aggregated('claims', db.Column(db.Integer))
def unpaid_amount(self):
return db.func.count('1')
# modules/accounting/models.py
class Claim(db.Model, OwnerMixin):
__owner_backref_name__ = 'claims'
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.DateTime, nullable=False)
label = db.Column(db.String, nullable=False)
amount = db.Column(db.Float, nullable=False)
ref = db.Column(db.String)
patient_id = db.Column(db.Integer, db.ForeignKey('patient.id'), nullable=False)
patient = db.relationship(
Patient,
backref=db.backref('claims', cascade="delete, delete-orphan")
)
Patient is in dedicated module "patient"
and claim model is in 'accounting' modules with other models related to accounting.
The problem is I can't import claim model and I can't access to claim model in patient model in order to, for example, make the sum of claims amount.
I think this is some design issue, but I want to be sure if there's any workaround before rewriting....
Hello Frol, how are you?
As you do to specify that it is necessary to use a token in the header, once your patch has made the @api.header notation stop working.
I want to use MongoDB for storing data. How to implement this in current code?
Looking at the example the swagger.json file it appears to be generating fields that are required.
For example: https://gist.github.com/xamox/7bf2fafedb303ec25f397dfb72fcaeb5#file-swagger-json-L1463
It says username required.
When I look at the schema, it appears to be using the model:
https://github.com/frol/flask-restplus-server-example/blob/master/app/modules/teams/schemas.py#L15
using this model:
https://github.com/frol/flask-restplus-server-example/blob/master/app/modules/teams/models.py#L21
Which seems to have a sqlalchemy relationship to the User model.
https://github.com/frol/flask-restplus-server-example/blob/master/app/modules/users/models.py#L41
The only place that I can see anywhere that it maybe required is in the users parameters.py file.
https://github.com/frol/flask-restplus-server-example/blob/master/app/modules/users/parameters.py#L25
But those other fields (email, password, recaptcha) are listed as required, but don't appear to be a required field in the swagger.yaml. Is there somewhere that is stripping them from being required? Or is it actually setup/propagated somewhere that I may not know about?
Here, you're trying to override _invalid_response
in OAuthProvider
object.
Do you really need this trick? AFAIU, the proper way to do this would be to register your custom function using invalid_response
.
Example using it as a decorator (as seen here):
@oauth.invalid_response
def require_oauth_invalid(req):
api.abort(code=http_exceptions.Unauthorized.code)
If create team by regular user and then try to GET /teams/:id we get
{
"message": "You don't have the permission to access the requested resource.",
"status": 403
}
It seems to happen because team is created without any member. I think the creator should become the first member of team.
Consider the folowing:
api = Namespace('users', description="Users")
........
@api.route('/<int:user_id>')
@api.resolve_object_by_model(User, 'user')
class UserByID(Resource):
...
@api.route('/<int:user_id>/accounts/')
Pretty straightforward, nesting "accounts" under the users namespace. I would like to split my resource into multiple files, seems simple enough:
api = Namespace('users', description="Users")
@api.route('/<int:user_id>')
api = Namespace('users', description="Users")
@api.route('/<int:user_id>/accounts/')
from .users import api as userApi
from .accounts import api as userAccountApi
from .logins import api as userLoginApi
from .resources import userApi, userLoginApi, userAccountApi
api_v1.add_namespace(userApi)
api_v1.add_namespace(userLoginApi)
api_v1.add_namespace(userAccountApi)
This does work, but gives some oddities in the swagger related test cases:
Failed validating 'uniqueItems' in schema['properties']['tags']:
E {'items': {'$ref': '#/definitions/tag'},
E 'type': 'array',
E 'uniqueItems': True}
E
E On instance['tags']:
E [{'description': 'Default namespace', 'name': 'default'},
E {'description': 'Authentication', 'name': 'auth'},
E {'description': 'Teams', 'name': 'teams'},
E {'description': 'Users', 'name': 'users'},
E {'description': 'Users', 'name': 'users'},
E {'description': 'Users', 'name': 'users'}]
How would one properly set this up?
I'm using the Resource Owner Password Flow. It works successfully, but it leaves out the expiration information. Here is the debug logging info:
2017-06-19 18:22:17,940 [INFO] [werkzeug] 127.0.0.1 - - [19/Jun/2017 18:22:17] "OPTIONS /auth/oauth2/token HTTP/1.1" 200 -
2017-06-19 18:22:17,952 [DEBUG] [flask_oauthlib] Fetched extra credentials, {}.
2017-06-19 18:22:17,953 [DEBUG] [oauthlib.oauth2.rfc6749.endpoints.token] Dispatching grant_type password request to <oauthlib.oauth2.rfc6749.grant_types.resource_owner_password_credentials.ResourceOwnerPasswordCredentialsGrant object at 0x105809358>.
2017-06-19 18:22:17,974 [DEBUG] [flask_oauthlib] Authenticate client 'documentation'.
2017-06-19 18:22:17,978 [DEBUG] [oauthlib.oauth2.rfc6749.grant_types.resource_owner_password_credentials] Validating access token request, <oauthlib.Request url="http://localhost:5000/auth/oauth2/token", http_method="POST", headers="{'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Content-Length': '172', 'Accept-Language': 'en-US,en;q=0.8,af;q=0.6', 'Accept': 'application/json, application/x-www-form-urlencoded', 'Referer': 'http://localhost:3000/', 'Connection': 'keep-alive', 'Origin': 'http://localhost:3000', 'Host': 'localhost:5000', 'Authorization': '<SANITIZED>', 'Accept-Encoding': 'gzip, deflate, br'}", body="{'password': 'q', 'scope': 'videos:read auth:read users:write auth:write users:read teams:read teams:write videos:write', 'username': 'root', 'grant_type': 'password'}">.
2017-06-19 18:22:17,979 [DEBUG] [oauthlib.oauth2.rfc6749.grant_types.resource_owner_password_credentials] Validating username root.
2017-06-19 18:22:17,979 [DEBUG] [flask_oauthlib] Validating username 'root' and its password
2017-06-19 18:22:18,307 [DEBUG] [oauthlib.oauth2.rfc6749.grant_types.resource_owner_password_credentials] Authorizing access to user <User(id=1, username="root", email="root@localhost", is_internal=False, is_admin=True, is_regular_user=True, is_active=True, is_enterprise=False, is_staff=False, is_employer=False, is_applicant=False, )>.
2017-06-19 18:22:18,307 [DEBUG] [oauthlib.oauth2.rfc6749.grant_types.base] Validating access to scopes ['videos:read', 'auth:read', 'users:write', 'auth:write', 'users:read', 'teams:read', 'teams:write', 'videos:write'] for client 'documentation' (<app.modules.auth.models.OAuth2Client object at 0x105889da0>).
2017-06-19 18:22:18,309 [DEBUG] [flask_oauthlib] Save bearer token {'refresh_token': 'PkAau0F3OubMMNxRtHtADPDcBSibHX', 'token_type': 'Bearer', 'expires_in': 3600, 'scope': 'videos:read auth:read users:write auth:write users:read teams:read teams:write videos:write', 'access_token': 'tYMLyLO6RE87H2w99HJaRs1qNBVY0x'}
2017-06-19 18:22:18,323 [DEBUG] [oauthlib.oauth2.rfc6749.grant_types.resource_owner_password_credentials] Issuing token {'refresh_token': 'PkAau0F3OubMMNxRtHtADPDcBSibHX', 'token_type': 'Bearer', 'scope': 'videos:read auth:read users:write auth:write users:read teams:read teams:write videos:write', 'access_token': 'tYMLyLO6RE87H2w99HJaRs1qNBVY0x'} to client id 'documentation' (<app.modules.auth.models.OAuth2Client object at 0x105889da0>) and username root.
2017-06-19 18:22:18,324 [INFO] [werkzeug] 127.0.0.1 - - [19/Jun/2017 18:22:18] "POST /auth/oauth2/token HTTP/1.1" 200 -
Here is the raw JSON returned:
{"refresh_token": "PkAau0F3OubMMNxRtHtADPDcBSibHX", "token_type": "Bearer", "scope": "videos:read auth:read users:write auth:write users:read teams:read teams:write videos:write", "access_token": "tYMLyLO6RE87H2w99HJaRs1qNBVY0x"}
It seems that it gets left out somewhere between flask-oauthlib and oauthlib logging output.
Is this expected behavior?
Hi @frol,
I was wondering if there were any plans about merging this patched version of Flask-RESTplus into the Flask-RESTplus repository some day (or making it a stand-alone package) ? So that it can be used independently from the rest of this example. Also would there be a very simple example somewhere (similar to the flask-restplus quickstart example) on how to use this patched version with marshmallow and webargs? Thank you!
Hi,
I would like to know what do you think about using this example for multi-tenant application.
Is it necessary to add some tenant table, or could I extend the Team model and use it as tenant model ? (because I don't need Team model anyway)
Let me know, thanks !
I'd like to have something like
invoke app.newmodule <name_of_my_module>
Which create an empty module with necessary stuff to create write a module.
Now we need to copy-paste some existing module then clean it and rewrite to have a new one. Just want to simplify this process.
@frol what do you think? What stuff if necessary for a new module.
BTW we can have similar task for new extension (it'd be better to create separate issue for that if you are interested)
UPDATE
And I don't like app.newmodule
it is first that came to my head, ready to discuss any variants :)
Hi there,
How can I enable debugger in this kit? I assumed it's already active but i get Internal Server Error and nothing shows up on console or browser.
makedirs fails if there exists a directory (tasks/app/dependencies.py)
There are several places to do this.
Hi,
This is obviously related to #70;
I have no idea how to implement these tests (and haven't searched yet) but would really want to help!
Here the validation cannot happen because data is always null.
I tried with @validates('recaptcha_key') and the method is never invoked.
Maybe I'm misusing it? I don't know.
EDIT: replaced link by cannonical url.
This feature will require to have a page for authentication since we don't have cookie sessions on RESTful API by design, just like in #3.
When I run py.test -x
I've got the error from subject.
I've checked no error with python 3, only with 2.7
Trace:
def test_create_app():
try:
> create_app()
tests/test_app_creation.py:10:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
app/__init__.py:61: in create_app
modules.init_app(app)
app/modules/__init__.py:17: in init_app
import_module('.%s' % module_name, package=__name__).init_app(app, **kwargs)
app/modules/auth/__init__.py:40: in init_app
api_v1.add_namespace(resources.api)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <app.extensions.api.api.Api object at 0x10bef97d0>, ns = <app.extensions.api.namespace.Namespace object at 0x10c1d2dd0>, path = None
def add_namespace(self, ns, path=None):
# Rewrite security rules for OAuth scopes since Namespaces don't have
# enough information about authorization methods.
for resource, _, _ in ns.resources:
for method in resource.methods:
method_func = getattr(resource, method.lower())
if (
hasattr(method_func, '__apidoc__')
and
'security' in method_func.__apidoc__
and
'__oauth__' in method_func.__apidoc__['security']
):
oauth_scopes = method_func.__apidoc__['security']['__oauth__']['scopes']
method_func.__apidoc__['security'] = {
auth_name: oauth_scopes
for auth_name, auth_settings in iteritems(self.authorizations)
if auth_settings['type'].startswith('oauth')
}
> super(Api, self).add_namespace(ns, path=path)
E TypeError: add_namespace() got an unexpected keyword argument 'path'
app/extensions/api/api.py:52: TypeError
imagine I have a profile linked to my user and I want to expose only one route (/users/) to patch the twos, is it actually possible ?
Seems like the actual implementation isn't compatible ? is it ?
I created two tuples and merged them with :
PATH_CHOICES = USER_CHOICES (as /%s) + PROFILE_CHOICES (as /profile/%s)
But I get this error :
marshmallow.exceptions.ValidationError: Field 'parts_number' does not exist, so it cannot be patched
Hello
I'm trying using PostgreSQL database to make your example work. I have problem with logs error like this
Traceback (most recent call last):
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
context)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute
cursor.execute(statement, parameters)
psycopg2.ProgrammingError: column "password" cannot be cast automatically to type bytea
HINT: You might need to specify "USING password::bytea".
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/me/.virtualenvs/flask-noota-api/bin/invoke", line 11, in
sys.exit(program.run())
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/invoke/program.py", line 293, in run
self.execute()
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/invoke/program.py", line 408, in execute
executor.execute(*self.tasks)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/invoke/executor.py", line 114, in execute
result = call.task(*args, **call.kwargs)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/invoke/tasks.py", line 114, in call
result = self.body(*args, **kwargs)
File "/home/me/CODER/python/flask-noota-api/tasks/app/_utils.py", line 61, in wrapper
return func(*args, **kwargs)
File "/home/me/CODER/python/flask-noota-api/tasks/app/db.py", line 277, in init_development_data
context.invoke_execute(context, 'app.db.upgrade')
File "/home/me/CODER/python/flask-noota-api/tasks/init.py", line 73, in invoke_execute
results = Executor(namespace, config=context.config).execute((command_name, kwargs))
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/invoke/executor.py", line 114, in execute
result = call.task(*args, **call.kwargs)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/invoke/tasks.py", line 114, in call
result = self.body(*args, **kwargs)
File "/home/me/CODER/python/flask-noota-api/tasks/app/_utils.py", line 61, in wrapper
return func(*args, **kwargs)
File "/home/me/CODER/python/flask-noota-api/tasks/app/db.py", line 163, in upgrade
command.upgrade(config, revision, sql=sql, tag=tag)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/alembic/command.py", line 174, in upgrade
script.run_env()
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/alembic/script/base.py", line 416, in run_env
util.load_python_file(self.dir, 'env.py')
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/alembic/util/pyfiles.py", line 93, in load_python_file
module = load_module_py(module_id, path)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/alembic/util/compat.py", line 68, in load_module_py
module_id, path).load_module(module_id)
File "", line 388, in _check_name_wrapper
File "", line 809, in load_module
File "", line 668, in load_module
File "", line 268, in _load_module_shim
File "", line 693, in _load
File "", line 673, in _load_unlocked
File "", line 665, in exec_module
File "", line 222, in call_with_frames_removed
File "migrations/env.py", line 93, in
run_migrations_online()
File "migrations/env.py", line 86, in run_migrations_online
context.run_migrations()
File "", line 8, in run_migrations
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/alembic/runtime/environment.py", line 807, in run_migrations
self.get_context().run_migrations(**kw)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/alembic/runtime/migration.py", line 321, in run_migrations
step.migration_fn(**kw)
File "/home/me/CODER/python/flask-noota-api/migrations/versions/36954739c63.py", line 28, in upgrade
existing_nullable=False)
File "/usr/lib/python3.5/contextlib.py", line 66, in exit
next(self.gen)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/alembic/operations/base.py", line 299, in batch_alter_table
impl.flush()
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/alembic/operations/batch.py", line 57, in flush
fn(*arg, **kw)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/alembic/ddl/postgresql.py", line 91, in alter_column
existing_nullable=existing_nullable,
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/alembic/ddl/impl.py", line 118, in _exec
return conn.execute(construct, *multiparams, **params)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/sqlalchemy/engine/base.py", line 945, in execute
return meth(self, multiparams, params)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/sqlalchemy/sql/ddl.py", line 68, in _execute_on_connection
return connection._execute_ddl(self, multiparams, params)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/sqlalchemy/engine/base.py", line 1002, in _execute_ddl
compiled
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context
context)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/sqlalchemy/engine/base.py", line 1393, in _handle_dbapi_exception
exc_info
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/sqlalchemy/util/compat.py", line 186, in reraise
raise value.with_traceback(tb)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
context)
File "/home/me/.virtualenvs/flask-noota-api/lib/python3.5/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) column "password" cannot be cast automatically to type bytea
HINT: You might need to specify "USING password::bytea".
[SQL: 'ALTER TABLE "user" ALTER COLUMN password TYPE BYTEA ']
tested with
installed dependencies
alembic==0.8.10
aniso8601==1.2.0
apispec==0.19.0
appdirs==1.4.2
arrow==0.8.0
bcrypt==3.1.3
cffi==1.9.1
click==6.7
colorlog==2.10.0
Flask==0.12
Flask-Cors==3.0.2
Flask-Login==0.4.0
flask-marshmallow==0.7.0
Flask-OAuthlib==0.9.3
flask-restplus==0.10.1
Flask-SQLAlchemy==2.2
invoke==0.15.0
itsdangerous==0.24
Jinja2==2.9.5
jsonschema==2.6.0
lockfile==0.12.2
Mako==1.0.6
MarkupSafe==0.23
marshmallow==2.13.1
marshmallow-sqlalchemy==0.12.0
oauthlib==2.0.1
packaging==16.8
passlib==1.7.1
permission==0.4.1
psycopg2==2.7
pycparser==2.17
pyparsing==2.1.10
python-dateutil==2.6.0
python-editor==1.0.3
pytz==2016.10
PyYAML==3.12
requests==2.13.0
requests-oauthlib==0.8.0
six==1.10.0
SQLAlchemy==1.1.5
SQLAlchemy-Utils==0.32.12
webargs==1.5.3
Werkzeug==0.11.15
any idea ?
If we add 'options'
to supportedSubmitMethods
here https://github.com/frol/flask-restplus-server-example/blob/master/app/templates/swagger-ui.html#L13
Then button 'Try it out' appears in Swagger under OPTIONS
block, but if we try to do a request we got an error in console.
Found a thread with issue that looks similar to current, tried to add code from the link to commit into swagger-ui.js
-- didn't help. Link to thread: https://groups.google.com/forum/#!topic/swagger-swaggersocket/K021AxKqXVM
Any plans on adding JWT token support? The Flask-JWT-Extended package seems to be fairly feature-complete.
I've looked over the other two json related issues and didn't see anything relating to my problem.
I'm setting my parameter to json:
@api.parameters(parameters.AddAnnouncementParameters(), locations=('json',))
configuring my parameters:
title = base_fields.String(required=True, location='json')
content = base_fields.String(required=True, location='json')
Then validation stops working, I'm allowed to submit blank strings for these fields.
ImportError: No module named migrations when run "invoke app.run"
Need to add init.py ?
0.9.0 release included a lot of breaking changes, including dropping Flask-RESTful dependency and improving namespaces support.
I am not able to use the validates
decorator using PatchJSONParameters
.
For example, using the following code raise a ValueError
(field does not exist) while there are fields in PATH_CHOICES
.
@validates('name')
def validate_name(self, data):
if len(data)<3:
raise ValidationError('Too short!')
I am not even sure that this is an issue as I don't know how I am supposed to do it. I can see there is already some code to map validators with patched fields in PatchJSONParameters.__init__
:
self.fields['op'].validators = \
self.fields['op'].validators + [validate.OneOf(self.OPERATION_CHOICES)]
self.fields['path'].validators = \
self.fields['path'].validators + [validate.OneOf(self.PATH_CHOICES)]
This is the accessCode
flow type in OpenAPI (Swagger) Specification.
This feature will require to have a page for authentication since we don't have cookie sessions on RESTful API by design, just like in #4.
This issue is related to #25.
/cc @khorolets
#26 showed that there might be a situation when all tests pass, the response is expected, but it was not explicitly covered with @api.response()
decorator. I think we will need to override Api.output
from flask_restplus/api.py
(note, there is already customization on Api class in flask_restplus_patched
, so you can just add this patch there), so we can check what responses are defined on the resource
, and the current response is expected (don't forget about special care around HTTP/500 internal error, this can happen anywhere and shouldn't be shadowed).
Currently, POST requests use query arguments, which is obviously not what most of the people would like to do.
Hello
I'm struggling with Alembic/SQLAlchemy to make your example work with PostgreSQL. The problem is related to the column_types.PasswordType in the users module's model.py file as described in this post:
Any idea?
Hi -
Thanks for a GREAT example! I am trying use it as the starting point for a small service I am writing. I do not seem to be able to get the custom validators and or pre and post request processing to work. However, I am not well versed in Marshmallow, so do not know if they are my problems or problems with the integration hack.
Would you consider adding a field to teams with a custom validator (I think this is the marshmallow way) The one I am trying to add is a custom date field, simplest case - existing or string 'now'.
The other things I am looking at integrating (once I have a bit more understanding about 'schemas' are:
guid instead of or in addition to id fields
jwt authentication (then I can separate out the oauth part)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.