Python Flask and Nginx-> routes redirection - python

I have an app, built with Flask-User and Flask-Login. This app is working.
I launch my app like :
app.run('0.0.0.0', 5000)
This app is running into a container, which is linking ports like XXXX:5000
My problem is that : On my server, I'm running my container. On this server, I also use nginx where I set a special url for this porject. The special url is : '/my_special_url'
The problem is that I can't redirect my app endpoints (like '/sign_up' or '/register') to the right urls defined by nginx (it must be '/my_special_url/sign_up' or '/my_special_url/register').
I tried to use url_prefix into the flask app, but it doesn't work.

Related

can't add header/Access-Control-Allow-Crendentials - python function app

I can get my signalr code to connect + work no problem in my local environment by setting host with web url
"Host": {
"LocalHttpPort": 7070,
"CORS": "http://localhost:4200",
"CORSCredentials": true
}
Then I deploy it to the portal and go to CORS and add the web url that my storage blob static website is hosted on inside CORS for the signalr function app. When I login to my app with the web url matching cors value I get this for some reason
Also according to the docs (bottom part of page) I have to enable Access-Control-Allow-Crendentials
but it seems that a function app running on python doesn't have that option
How can I enable Access-Control-Allow-Crendentials in a python function app?
Yes, there is no way to set it on azure portal. Not only 'Access-Control-Allow-Crendentials', but also many other config settings cannot set by using azure portal when you are based on linux web app.
To achieve that you want, you can use below cmd in powershell:(It works when you are based on azure web app. azure function is based on web app sandbox, so below cmd also works on function.)
az resource update --name web --resource-group yourresoursegroupname --namespace Microsoft.Web --resource-type config --parent sites/yourfunctionname --set properties.cors.supportCredentials=true
This is the offcial doc:
https://learn.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-rest-api#enable-cors
If your app requires credentials such as cookies or authentication
tokens to be sent, the browser may require the
ACCESS-CONTROL-ALLOW-CREDENTIALS header on the response. To enable
this in App Service, set properties.cors.supportCredentials to true in
your CORS config. This cannot be enabled when allowedOrigins includes
'*'.
On my side, I can change the config setting. Let me know whether you can change the config.:)

How to get the user location from the web app running on Heroku?

I am having a problem that when I get user location by using http://freegeoip.net/json, it seems to get the location from where the Heroku server is located.
I used Flask to make the web app.
I uploaded the web app through Heroku.
Per the api docs here you need to pass the ip of the user like 'http://freegeoip.net/json/%s' % request.remote_addr. Otherwise it will return the location of the requester, which in your case is your heroku server.

How to redirect http to https with Gunicorn

I use Flask as Web Application, to redirect http to https, I added such codes in app.py:
#app.before_request
def before_request():
if request.url.startswith('http://'):
url = request.url.replace('http://', 'https://', 1)
return redirect(url, code=301)
if __name__ == '__main__':
app.run()
and the gunicorn command in supervisor.conf is:
command=/home/MyToDo/venv/bin/gunicorn --certfile=/home/MyToDo/SSL/mytodo.vip.cer --keyfile=/home/MyToDo/SSL/mytodo.vip.key -w3 -b0.0.0.0:443 -b0.0.0.0:80 app:app
but when I visit the website, I still need to add "https://" in front the url, it didn't redirect automaticly. So how to make gunicorn redirect http to https, does using Nginx is the only way?
I had the same problem running Flask on Google App Engine Flexible environment with gunicorn. Solved by using werkzeug.contrib.fixers.ProxyFix of Werkzeug version 0.14.1.
from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
I had the same issues using Google App Engine and have spend too much time on this since all the answers including werkzeug.contrib.fixers.ProxyFix and the official docu's custom HTTPMethodsOverrideMiddleware or other custom solutions did not work for me.
I finally managed to solve this by configuring gunicorn using a config which sets:
secure_scheme_headers = {'X-FORWARDED-PROTO': 'https'} and forwarded_allow_ips = '*'
Additionally, for the ones wanting to serve static files and who are struggling with unwanted http redirects, adding handlers for each static directory in the .yaml configuration and avoiding nested sub-directories solved this issue.
Flask==2.1.3
gunicorn==20.1.0

How to configure flask session behind iis reverse proxy (wfastcgi)?

I'm configuring my flask app to run under iis with a reverse proxy. Basically my setup is like this:
external.domain.com:8000 ->
Reverse Proxy IIS ->
interal.network.net ->
iis (wfastcgi/flask)
The app's urls and content is loading correctly, but anything that deals with a session is not working:
Message flashing - no messages are flashed
Login cookies - not able to login at all
I've configured the flask app with these relevent config variables:
SERVER_NAME = 'internal.network.net'
SESSION_COOKIE_DOMAIN = 'external.domain.com'
I have an IIS rewrite rule set up on the external server:
Pattern: (.*)
Rewrite URL: http://internal.network.net/{R:1}
Is there anything else I need to configure to get sessions working correctly?
Not sure if this is the correct way of doing things but apparently excluding the properties SERVER_NAME and SESSION_COOKIE_DOMAIN actually fixes the issue.
Hope this helps someone.

Angular-cli with any other server

I'm relatively new to Angular 2, and I'm trying to build an app using the angular-cli system. This works and I can ng-serve and the application comes up. However, it seems like a huge pain in the ass to try and serve the application with anything other than the ng-serve system. In particular I'm trying to serve the application built with angular-cli with a Python Flask app. The amount of hoops I'm seemingly having to jump through trying to get this to work is making me crazy! I want to do this because I want to serve a REST API with the Python/Flask app that will respond to the HTTP services requests from the Angular 2 application.
Here are the relevant versions I'm using:
node - 6.2.2
npm - 2.9.5
angular 2 - rc.4
angular-cli - 1.0.0-beta.9
python - 2.7.5
flask - 0.10.1
How can I serve an Angular app while using Flask?
I've actually sort of solved the problem. I have a directory named "smoke" (short for smoke and mirrors ), and inside there I ran the angular-cli command:
ng new static
This created the angular-cli start out application in the static directory. Then I created this (simplified) Python Flask application:
import os
from flask import Flask, send_from_directory, redirect
from flask.ext.restful import Api
from gevent import monkey, pywsgi
monkey.patch_all()
def create_app():
app = Flask("press_controller")
# map the root folder to index.html
#app.route("/")
def home():
return redirect("/index.html")
#app.route("/<path:path>")
def root(path):
"""
This is the cheesy way I figured out to serve the Angular2 app created
by the angular-cli system. It essentially serves everything from
static/dist (the distribution directory created by angular-cli)
"""
return send_from_directory(os.path.join(os.getcwd(), "static/dist"), path)
return app
if __name__ == "__main__":
app = create_app()
server = pywsgi.WSGIServer(("0.0.0.0", 5000), app)
server.serve_forever()
else:
app = create_app()
This way I can navigate to http://localhost:5000 and the application will serve up the Angular app just like "ng serve" does. Now I can add in my REST API endpoints as I wanted and have Angular services access them to populate the application.
There's no requirement that Flask serves the frontend application.
Really all Flask would be doing with an Angular app is serving static files, something that is better handled by a web server like Nginx in production, or the framework's tools like ng-serve in development.
Meanwhile, Flask would act as the backend api server that your frontend app communicates with. Use request.get_json() and return jsonify(...) to get and respond with JSON data.
Run the two separately, they work together over HTTP only. This also simplifies working with backend vs. frontend developers: all they need to know about is the api to communicate between the two. However, since the frontend is being served on a different port than the backend, you'll need to set up Flask appropriately to allow CORS requests, for example with Flask-CORS.
Old question but I came across it when setting up my new project. I'm using a a more recent version of angular cli (7.3.1) and Flask (1.0.2) but the setup is pretty similar to yours. I should note that this is by no means the cleanest setup, and I'm sure the same could be achieved with webpack only, but I felt this way was a bit easier to follow (I've found webpack config can be a nightmare). My directory structure is as follows (after building):
client // this is my angular project
src
angular.json
server // this is my flask server
templates
index.html // generated from ng build
static
vendor.js // generated from ng build
pollyfills.js
...
Makefile
In angular.json, you'll want to point the build path to your flask server:
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {
"outputPath": "../server/static",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": [],
"es5BrowserSupport": true
},
...
In my server, configure the static url:
app = Flask(__name__, static_url_path='')
And finally in the makefile, execute the build command, and copy the template file into the templates folder:
all:
cd client && ng build --prod;
mv server/static/index.html server/templates/ ;
.PHONY : all
Again, not the most elegant solution but pretty straight forward to get rolling with the angular cli (rather than getting the hands dirty with webpack).

Categories

Resources