Angular-cli with any other server - python

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).

Related

Python Flask and Nginx-> routes redirection

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.

Serve Dash plotly app with Twisted Web Server

Dash is a dashboard-related python library that is based on Flask. The default dash app will run a Flask server, which is as they stated, "not recommended for production environment". I have managed to find Twisted library which can do decent html handling. The problem is, I know how to use Twisted to host flask sites, but I do not know how to do the same for dash app. There is a nice library which integrates both flask and twisted together.
https://github.com/cravler/flask-twisted
To use it, one just need to use the following lines:
server = flask.Flask(__name__)
app = dash.Dash(__name__, server = server)
twisted = Twisted(server)
twisted.run(host='0.0.0.0',port=8050, debug=False)
Now, for learning purposes, I am trying to recreate the same functionality without flask-twisted. I tried my best to follow the source code in the module but still cannot recreate the same result. The page http://127.0.0.1:8082/my_flask/ is stuck at "Loading...". What did I do wrong?
if __name__ == '__main__':
resource = WSGIResource(reactor, reactor.getThreadPool(), server)
site = Site(WSGIRootResource(resource, {}))
server.run
root = Resource()
root.putChild(b'my_flask', site)
reactor.listenTCP(8082, Site(root))
reactor.run()

Is there an arg to set other endpoint in start_http_server (prometheus_client) instead of /?

I'm building a Flask application and I would like to know if there is an arg on module start_http_server (from prometheus_client) that allow me to set a specific metrics endpoint instead /.
Thanks!
When using the Prometheus client with flask, you don't need to start the http server on your own but you can enable the wsgi middleware and specify the route you want to serve your metrics on your existing app.
app = Flask(__name__)
app_dispatch = DispatcherMiddleware(app, {
'/metrics': make_wsgi_app()
})
For the full example how to do this, just check out the python prometheus_client docs on flask.

Cloud9 "Unable to load http preview" Flask project

I'm following a mooc for building quickly a website in flask.
I'm using Cloud9 but i'm unable to watch my preview on it, i get an :
"Unable to load http preview" :
the code is really simple, here the views.py code
from flask import Flask, render_template
app = Flask(__name__)
# Config options - Make sure you created a 'config.py' file.
app.config.from_object('config')
# To get one variable, tape app.config['MY_VARIABLE']
#app.route('/')
def index():
return "Hello world !"
if __name__ == "__main__":
app.run()
And the preview screen, is what I get when I execute
python views.py
Thank you in advance
you need to make FLASK_APP environment variable, and flask application is not running like python views.py but flask run. Quick start
# give an environment variable, give the absolute path or relative
# path to you flask app, in your case it is `views.py`
export FLASK_APP=views.py
#after this run flask application
flask run
I faced the same problem. There is no way we can preview http endpoints directly. Although in AWS documentation they have asked to follow certain steps, but those too wont work. Only way is to access it using instance public address and exposing required ports. Read here for this.

Getting the Server URL in Google App Engine using python

How do I get App Engine to generate the URL of the server it is currently running on?
If the application is running on development server it should return
http://localhost:8080/
and if the application is running on Google's servers it should return
http://application-name.appspot.com
You can get the URL that was used to make the current request from within your webapp handler via self.request.url or you could piece it together using the self.request.environ dict (which you can read about on the WebOb docs - request inherits from webob)
You can't "get the url for the server" itself, as many urls could be used to point to the same instance.
If your aim is really to just discover wether you are in development or production then use:
'Development' in os.environ['SERVER_SOFTWARE']
Here is an alternative answer.
from google.appengine.api import app_identity
server_url = app_identity.get_default_version_hostname()
On the dev appserver this would show:
localhost:8080
and on appengine
your_app_id.appspot.com
If you're using webapp2 as framework chances are that you already using URI routing in you web application.
http://webapp2.readthedocs.io/en/latest/guide/routing.html
app = webapp2.WSGIApplication([
webapp2.Route('/', handler=HomeHandler, name='home'),
])
When building URIs with webapp2.uri_for() just pass _full=True attribute to generate absolute URI including current domain, port and protocol according to current runtime environment.
uri = uri_for('home')
# /
uri = uri_for('home', _full=True)
# http://localhost:8080/
# http://application-name.appspot.com/
# https://application-name.appspot.com/
# http://your-custom-domain.com/
This function can be used in your Python code or directly from templating engine (if you register it) - very handy.
Check webapp2.Router.build() in the API reference for a complete explanation of the parameters used to build URIs.

Categories

Resources