Flask and url rewrite - python

Is it possible to do url rewrite with Flask under Nginx+uWSGI?
I need to add SEO links, so pages of Flask website should be available with two links, for example:
/post/3 and /2014_10_08_post_title.
Connections between normal link and SEO link should be stored in database.
What is the easist way to do it? Is it better and faster way to do it within Flask app or it can be done within nginx?
Thanks!

Flask allows routing multiple URLs to the same view:
#route('/post/<post_id>', defaults={'seo_url': None})
#route('/<seo_url>', defaults={'post_id': None})
def view(post_id, seo_url):
if post_id:
...
elif seo_url:
...

Related

Flask routing by username at top-level route

Is there a prefered way of setting up Flask so that it routes by username (mysite.com/<username>) at the top level but still works well (and fast) for all other routes and static files?
The way I imagine it now is something like:
#app.route('/<username>', methods=['GET'])
def username_route(username):
if username_is_valid(username): # DB checks, not too fast
display_user_page(username)
render_template('user_not_found.html')
But would that have any unwanted effects on other routes or static assets, favicons, or something that I'm forgetting?
You can send data with post request on frontend for clicking profile cases.
<button onclick="urlfor('username', {'user_id': id})"/>
Top level solution is possible with app.config.
app.config['RESERVED_ROUTES'] = [
"faqs",
"settings",
"login",
...
]
Now we decide on request are user or reserved route. Because when we want to use blueprint in Flask it copy the config and give them an instance. So it is reachable for every request even you want to scale your app with blueprints.
#app.before_request
def decide_user_or_not():
if request.path in app.config['RESERVED_ROUTES']:
register_blueprint(route_blueprint)
else:
register_blueprint(user_blueprint)
Put your username_route at the end. Flask checks for each route from top to bottom. So, when you put faqs_route at the top which points to mysite.com/faqs, flask will consider that first.
Now, if you want to go to mysite.com/<username>, it will check all the top functions and since it can't find the corresponding route, it will go to the username_route at the end which will be the right route for mysite.com/<username>

How to create a private endpoint in flask

In my flask application I need to fetch data from my database whenever the users clicks a button, I know I can just make a flask route, using the flask restful module or plain routes. But my question is if I can make that route/endpoint not visible for users.
#app.route("/api/fetch/")
def fetch_data():
return some_data
I dont wan't the user having access to this endpoint directly, I just want the web application to be able to use it. Not sure if it is possible or where to look.
I found that maybe using Flask-CORS could help. Any help or guidance would be appreciated.
On flask you can use Blueprint
example from the above snippet would be
from flask import Blueprint
sample_bp = Blueprint("sample_bp", __name__)
#sample_bp.before_request
def restrict_with_token():
# Do something here on checking header or token
#sample_bp.route("/api/fetch/")
def fetch_api():
# Your logic
Otherwise you can have some referrence here : https://flask.palletsprojects.com/en/1.1.x/tutorial/views/

Accessing cookie from another sub-domain

I have two django applications that are deployed at two different sub-domains, for example:
data.mysite.com
i.mysite.com
Both sites use the same django authentication framework and such, setting a cookie called sessionid. I can read the cookie from the current site using:
def my_view(request):
# suppose this view is within the i.mysite.com application
i_session_id = request.COOKIES['sessionid']
data_session_id = ? # how to get this?
But then how could I grab the cookies from the
If you want to have a shared authentication between your 2 subdomains then you need to set your session on .mysite.com domain. Then when you request to data.mysite.com will include this cookie, same for i.mysite.com domain. So, in settings.py:
SESSION_COOKIE_DOMAIN=".mysite.com"

How should an index.html file be served from Python Pyramid for an AngularJS app?

I am getting into single-page apps with AngularJS but rather than using Node or similar, I am most comfortable with Python on the server. So, given I am somewhat familiar with Pyramid, I plan to use the pyramid_rpc module to return JSON objects to the client app. That's all straight forward enough, however, what then is the best way to serve the starting index file which contains the AngularJS initial AngularJS app? Usually, static files are served from a static directory, but is there any problem serving a index.html file from the root? Or should I use a view-callable and '/' route with a renderer to a html template? All that being said, is Pyramid overkill for this kind of application? Any advice would be great.
If you're planning to return some JSON responses then Pyramid is a great option. But I wouldn't recommend using pyramid_rpc. JSON-RPC is a protocol that is intended for RPC communication between servers. Straight json responses fit most clients (like browsers) better such as just a bunch of routes that return JSON responses in response to GET/POST requests. This is also a good place to serve up index.html, probably with a good http_cache parameter to prevent clients from requesting that page too often (of course you can go further with optimizing this route, but you should probably save that for later).
config.add_route('index', '/')
config.add_route('api.users', '/api/users')
config.add_route('api.user_by_id', '/api/users/{userid}')
#view_config(route_name='index', renderer='myapp:templates/index.html', http_cache=3600*24*365)
def index_view(request):
return {}
#view_config(route_name='api.users', request_method='POST', renderer='json')
def create_user_view(request):
# create a user via the request.POST parameters
return {
'userid': user.id,
}
#view_config(route_name='api', request_method='GET', renderer='json')
def user_info_view(request):
userid = request.matchdict['userid']
# lookup user
return {
'name': user.name,
}

Pylons Routes url_for for a map.resource

How do I get the get, post, put and delete URLs for a restful routes resource using url_for?
For example, how do I get the PUT URL for a resource with id=1, and routes defined in routing.py like so:
map.resource('user', 'users', controller='user')
I know the correct URL is /users/1, but I don't want to hard code it.
Check out: http://routes.groovie.org/restful.html
url('user', id=1)
should give you '/users/1'
In routes.py your route should be:
map.resource('user', 'users/{id}', controller='user' action="some_action")
and in your controller you can get this URL with url_for like this:
url_for(controller="user", action="some_action", id=1)
Ref: Chapter 9: URLs, Routing and Dispatch, Pylons book.
I must warn you that this was used in Pylons 0.9.7, but it is not used in Pylons 1.0. url_for and redirect_to are redesigned. If you want to redirect in your controller you must write:
redirect(url(controller="user", action="some_action", id=1))
Or in your case:
url(controller="user", action="some_action", id=1)
Ref.: Pylons 1.0 Released

Categories

Resources