Is there a way to create Swagger-API UI documentation for a flask-potion based application?
I've tried using "flasgger", but it doesn't work for routes that are written with potion-type routes.
Flask-potion has a route specified in following manner-
#Route.GET('/num_products')
But "flasgger" expects a route in following manner-
#app.route('/num_products', methods=['GET'])
There is no clean way to do this. However, a hackish solution for the same exists-
Flasgger works for default flask routes. We can re-define the routes that were defined earlier using flask-potion, as default flask routes and make calls to the earlier flask-potion functions from the newly created functions. Note- Changing the existing routes to the new routes didn't work for me. I had to mask the old calls with new ones and call the old function from the new ones.
Note- This only works for custom routes that are written by the user and doesn't work for default routes that are generated from data model by flask potion.
Existing code-
class ProductResource(BaseModelResource):
#Route.GET('/num_products')
def product_count():
return product.query(...)
Refactored Code -
class ProductResource(BaseModelResource):
def product_count():
return product.query(...)
#app.route('/num_products', methods=['GET'])
def product_count_main():
output = product_count()
Response(str(output), content_type='application/json')
Related
So I have a django app with some models which I can manipulate via admin and also through a client facing site, like add instances etc. However, I would like to try something a little different from that. I have a Python script that uses POST and JSON objects based on those self same models and I would like to be able to run it, connect to my django app server via a port and create new instances of my models (essentially without using Admin or my client page). Any ideas how I go about this?
If what the script does is simple, it may be easiest just to create a view which receives the JSON, processes it, and returns a JsonResponse.
e.g.
def create_object(request):
if request.method == 'POST':
data = json.loads(request.body)
# Do something with the data - e.g. create a model instance
MyModel.objects.create(**data)
return JsonResponse({'status': 'created'})
Alternatively, if the script does more complicated things or if you intended to expand it in future, you may be best to expose your site via a REST API using something such as Django Rest Framework.
With Django Rest Framework, you can fairly rapidly build CRUD based APIs around your models using components such as ModelViewSets and ModelSerializers and expose them over REST with minimal code.
I want to move some commonly used parts of my webapps to Flask blueprints for better reuse. But some of the routes will need functionality which is specific to a webapp. An example would be a simple form submission where everything is handled by the blueprint, only the form validation would have to be defined by the implementing app.
How can I tell a blueprint view to call a function of the app. With inheritance I would create a abstract function which would be filled out by them implementing webapp. But I am lost how to do something similar with a blueprint.
Edit:
I am using Class based views, but the following snippet trys to explain what I am looking for:
#my_blueprint.route('/submit')
def submit():
errors = current_app.check_for_errors(request.form) # <--- How to?
return render_template('result.html', errors=error)
The errors = current_app.check_for_errors(request.form) is the one I don't know ho to implement. Sub-classing flask.Flask is the only way I can come up with, but this doesn't feel right.
I've read about blueprints in Flask but I think my app is too small to use it yet. However I would like to keep my code clear. Since my app has a user login I would like to keep several functions protected. Now I'm wondering if the following code is as safe as putting all the code into a route or is that not proper coding?
import scriptwithseveralfunctions.py
#app.route('/functionone')
#login_required
def do_something():
scriptwithseveralfunctions.myfunction()
Yes, it's definitely safe. Only functions with #app.route wrapper will be exposed to the user.
I have built flask apis in the past, but I've never had the luxury of being on a project where I was allowed to do test driven development while working on one. Now I am.
Every how-to I've ever read shows flask-apis being defined in a decidedly non-object-oriented style. This makes writing unit tests very difficult because one cannot pass optional or test-specific parameters into the instantiated api.
For example, this blog explains one method for creating unit tests for a flask-api:
http://mkelsey.com/2013/05/15/test-driven-development-of-a-flask-api/
The blog sets an environment variable when in test mode and the script watches for that variable, altering its behavior when it is found. This seems very inadvisable to me. There are a long list of reasons why letting your source code bleed into your OS environment is a Bad Idea. I'm a big believer in encapsulating functionality in order to maximize portability and to draw clear distinctions between where modules begin and end.
In order to satisfy my coding philosophy someone might suggest I just wrap the flask API up in a class. However, it isn't clear to me how one would do such a thing. For example, Flask uses decorators in order to define a route:
#app.route()
How could this be fit into a class?
I would greatly appreciate the guidance of anyone who has developed a flask api in an object oriented manner.
You can replace the use of #app.route with add_url_rule.
To put it in an example:
from flask import Flask
class MyFlaskApp:
def __init__(self):
self.app = Flask(__name__)
self.app.add_url_rule('/', 'index', self.index)
def index(self):
pass
Which is similar to:
from flask import Flask
app = Flask(__name__)
#app.route('/index')
def index():
pass
I have a couple of functions that I wrote that I need to use in my django app. Where would I put the file with them and how would I make them callable within my views?
I usually put such app specific helper function in file utils.py and use someting like this
from myapp.utils import my_cool_func
def view_coolness(request):
data = my_cool_func(request)
return render_to_response("xxx.html")
but it depends what you helper does, may be they modify request , the could be part of middleware, so you need to tell what exactly those helper functions do
create a reusable app that include your generic functions so you can share between projects.
use for example a git repo to store this app and manage deployments and evolution (submodule)
use a public git repo so you can share with the community :)
If they are related to a specific app, I usually just put them in the related app folder and name the file, 'functions.py'.
If they're not specific to an app, I make a commons app for components (tests, models, functions, etc) that are shared across apps.
I am using new python file service.py in app folder. The file contains mostly helper queries for specific app. Also I used to create a folder inside Django application that contains global helper functions and constants.