Running a Pyramid WSGI application under tornado - python

Pyramid uses it's own Waitress web server for development purposes, but I want to serve my WSGI app under Tornado. I think I should configure it using the pserve .ini files, but I can't get it to work

The Pyramid application can be loaded from the INI files easily. From there you just pass the wsgi app into Tornado's WSGIContainer.
from pyramid.paster import get_app
app = get_app('development.ini')
container = tornado.wsgi.WSGIContainer(app)

Again, not really recommending running WSGI under Tornado, since it gives you none of the advantages of Tornado.
Should you still want to do it for some reason, the second example of the docs seems to be what you are looking for: http://www.tornadoweb.org/documentation/wsgi.html
def simple_app(environ, start_response):
status = "200 OK"
response_headers = [("Content-type", "text/plain")]
start_response(status, response_headers)
return ["Hello world!\n"]
container = tornado.wsgi.WSGIContainer(simple_app)
http_server = tornado.httpserver.HTTPServer(container)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()

Related

How to serve Tornado with Django on waitress?

I have this tornado application wrapped with django function as WSGI app (using in windows)
from django.core.wsgi import get_wsgi_application
from django.conf import settings
from waitress import serve
settings.configure()
wsgi_app = tornado.wsgi.WSGIContainer(django.core.wsgi.WSGIHandler())
def tornado_app():
url = [(r"/models//predict", PHandler),
(r"/models//explain", EHandler),
('.*', tornado.web.FallbackHandler, dict(fallback=wsgi_app))]
return Application(url, db=ELASTIC_URL, debug=options.debug, autoreload=options.debug)
if __name__ == "__main__":
application = tornado_app()
http_server = HTTPServer(application)
http_server.listen(LISTEN_PORT)
IOLoop.current().start()
Not sure how to use waitress,
To serve using waitress I tried http_server = serve(application), server is starting, now sure is it correct, getting error when hitting the endpoint
waitress is a WSGI server; Tornado is not based on or compatible with WSGI. You cannot use waitress to serve the Tornado portions of your application.
To serve both Tornado and WSGI applications in one thread, you need to use Tornado's HTTPServer as you've done in the original example. For better scalability, I'd recommend splitting the Tornado and Django portions of your application into separate processes and putting a proxy like nginx or haproxy in front of them.

How to serve Flask With Http Server [duplicate]

This question already has answers here:
Are a WSGI server and HTTP server required to serve a Flask app?
(3 answers)
How to serve static files in Flask
(24 answers)
How to run functions in parallel?
(8 answers)
Closed 3 years ago.
I would like to develop an app that uses both Flask and httpd.
Flask publishes HTML-related files, and httpd publishes files in local files.
It is for browsing local files published in httpd from Flask HTML.
Though the port numbers of Flask and httpd are different, it seems that httpd server side is not working.
Connection refused error occurs when connecting to httpd server.
Added the intention of the question.
I want to run Flask's built-in web server and HTTPServer simultaneously from a script.
I just want to be able to see myself, not to expose it to the network.
I'm looking for a mechanism that can be completed with the app.py script without using WSGI.
Added additional information to the question.
This question uses Flask and Python's HTTPServer, but using NodeJS's HTTPServer instead of HTTPServer seems to work well.
(Comment out run())
I would like to complete in Python if possible without using NodeJS HTTPServer.
https://www.npmjs.com/package/http-server
C:\Users\User\Videos>http-server
Starting up http-server, serving ./
Available on:
http://127.0.0.1:8080
Hit CTRL-C to stop the server
...
version
Flask==1.0.2
Python 3.7
Can I not start each server with the following code?
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<video src="http://localhost:8080/video.mp4"></video>
</body>
</html>
python(app.py)
from http.server import SimpleHTTPRequestHandler, HTTPServer
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
return render_template('index.html')
class Handler(SimpleHTTPRequestHandler):
def __init__(self, *args, directory=None, **kwargs):
super().__init__(*args,
directory=r'C:\Users\User\Videos',
**kwargs)
def run(server_class=HTTPServer, handler_class=Handler):
server_address = ('localhost', 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
if __name__ == '__main__':
app.run(host='localhost', port=5000)
run()
It may not have been transmitted well. I'm sorry.
Thank you very much.
Can I not start each server with the following code?
Yes, there are many other ways.
WSGI
wsgi, which stands for Web Server Gateway Interface is defined in PEP 333:
This document specifies a proposed standard interface between web
servers and Python web applications or frameworks, to promote web
application portability across a variety of web servers.
framework side
flask, django and many other frameworks all implement this interface. So when you write an app in flask, app implements wsgi so any web server that knows how to serve a wsgi app can serve it.
web server side
There are many choices and you can find more at wsgi.org:
gunicorn
uWSGI
...
Basically, you can choose any of these to start your server and use httpd to proxy requests to it. Or you can use mod_wsgi:
mod_wsgi is an Apache module that embeds a Python application within
the server and allow them to communicate through the Python WSGI
interface as defined in the Python PEP 333.
Note
The bundled server in flask is not suitable for production use, you can see this question for more details.
For Updated Question
I want to run Flask's built-in web server and HTTPServer
simultaneously from a script.
Just Run Shell Command
You can start another process and call shell command using Popen:
if __name__ == '__main__':
p = Popen(['python -m http.server'], shell=True)
app.run(host='localhost', port=5000)
Use whatever command you like, you can even start a node http server here.
Use Thread/Process
You can start http server in another thread or process, here I use threading for example:
if __name__ == '__main__':
from threading import Thread
Thread(target=run, daemon=True).start()
app.run(host='localhost', port=5000)
Use Flask To Serve File
Instead of starting two servers binding to two ports, you can actually use flask to serve file as well. In this way, you only start one server binding to one port:
#app.route('/videos/<path:filename>')
def download_file(filename):
return send_from_directory(r'C:\Users\User\Videos',
filename, as_attachment=True)
You can see documentation for more details.
app.run() is a blocking operation. The below lines won't be interpreted.
Run your apps from separate files or in different thread/process.

Docker and WSGI with a Python Pyramid app?

I am looking at two articles on how to Dockerize a Pyramid app. I am not that familiar with Python, but I am fairly certain with a Pyramid app you need to use WSGI.
This article uses WSGI:
https://medium.com/#greut/minimal-python-deployment-on-docker-with-uwsgi-bc5aa89b3d35
This one just runs the python executable directly:
https://runnable.com/docker/python/dockerize-your-pyramid-application
It seems unlikely to me that you can run python directly and not incorporate WSGI, can anyone provide an explanation for why the runnable.com article's docker solution would work?
Per the scripts in the second link:
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
~snip~
if __name__ == '__main__':
config = Configurator()
config.add_route('hello', '/')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app() # The wsgi server is configured here
server = make_server('0.0.0.0', 6543, app) # and here
This contains an explanation of why the wsgi server is built in the if __name__=="__main__" block

Interfacing BaseHttpServer to WSGI in python

I am taking a python course where they use BaseHTTPServer. The code they start with is here
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class webServerHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path.endswith("/hello"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
message = ""
message += "<html><body>Hello!</body></html>"
self.wfile.write(message)
print message
return
except IOError:
self.send_error(404, 'File Not Found: %s' % self.path)
def main():
try:
port = 8080
server = HTTPServer(('', port), webServerHandler)
print "Web Server running on port %s" % port
server.serve_forever()
except KeyboardInterrupt:
print " ^C entered, stopping web server...."
server.socket.close()
if __name__ == '__main__':
main()
I am using python anywhere and there the only possibility to get an application onto the internet is to use an wsgi interface.
A configuration file for the wsgi interface looks like this:
import sys
path = '<path to app>'
if path not in sys.path:
sys.path.append(path)
from app import application
application could be something like this:
def application(environ, start_response):
if environ.get('PATH_INFO') == '/':
status = '200 OK'
content = HELLO_WORLD
else:
status = '404 NOT FOUND'
content = 'Page not found.'
response_headers = [('Content-Type', 'text/html'), ('Content-Length', str(len(content)))]
start_response(status, response_headers)
yield content.encode('utf8')
HELLO_WORLD would be a string with html content.
I cannot just point to port 8080 as in the example. In order to use python anywhere I do have to interface both. I reckoned it could be possible that the wsgi is derived from BaseHTTPServer so it might be possible to interface them and to use my course on pythonanywhere.com
It is clear I have to get rid in the code in the main function and use the application function instead. But I am not exactly getting how this works. I get a callback (start_response) which I call and then I yield the content? How can I combine this with the webServerHandler class?
If this would be possible it should in theory work as well for the google app engine. I found a very complex example here where BaseHTTPServer is used but this is too complex for me yet.
Is it possible to do this and if yes could someone give me a hint how to do this and provide me with some basic start code?
So WSGI is a specification that defines an interface between a request and a webapp. ie. when it receives a http request, it will pass it along to the webapp in a standardized way as described in the specification (eg: it must set this environment variable, it must pass this argument, it must make this call etc).
On the other hand, BaseHTTPServer both defines an interface and also has code that actually serves web requests.
This is a little used interface that is implemented almost exclusively by SimpleHTTPServer from the python2 standard library (or http.server in python3), and the server is not intended for anything production-ready.
This is because SimpleHTTPServer was designed mainly for developing locally. For example, it helps you get past js cross origin request problems when testing on localhost.
Nowadays, WSGI has become the de facto standard for python webapps, and so most websites written in python separate out the server / interface-y functionality that receives and implements the WSGI requirements from the webapp-y stuff.
In your code, you have a single piece of code that does both the "webapp-y" stuff and also the "process the http request / interface-y" stuff. This is not wrong, and is great for getting some basic understanding of how servers process http requests etc.
So my suggestion would be:
if your class is going to start using any python webapp frameworks soon anywahs, (eg: django, flask, , bottle, web2py, cherrypy etc), then you could potentially just wait till then to use pythonanywhere.
if your class is focused on digging into the nitty gritty of servers, you could refactor out the "webapp-y" layer from your code, and just use the "webapp-y" layer on PythonAnywhere. Locally, you would start the "server/interface-y" stuff that then imports your "webapp-y" to generate a response. If you successfully do this, then congrats! You have (kind of) just written a server that supports WSGI.

BottlePy App and CherryPy server not logging access

I'm serving a BottlePy App with CherryPy like this:
import cherrypy
from myapp import MyApp
from beaker.middleware import SessionMiddleware
appdir = '/path/to/app'
app = MyApp(appdir)
session_opts = {
'session.timeout': 600, # 10 minutes
'session.type': 'file',
'session.auto': True,
'session.data_dir': appdir + '/auth/data'
}
app = SessionMiddleware(app, session_opts)
cherrypy.tree.graft(app, '/')
cherrypy.config.update({
'log.screen': False,
'log.access_file': appdir + '/front_end/cherrypy.access.log',
'log.error_file': appdir + '/front_end/cherrypy.error.log',
'server.socket_port': 8080,
'server.socket_host': '0.0.0.0'
})
cherrypy.engine.start()
cherrypy.engine.block()
Everything seems to be working properly, but cherrypy.access.log remains totally empty, while cherrypy.error.log reads:
[30/Dec/2014:11:04:55] ENGINE Bus STARTING
[30/Dec/2014:11:04:55] ENGINE Started monitor thread '_TimeoutMonitor'.
[30/Dec/2014:11:04:55] ENGINE Started monitor thread 'Autoreloader'.
[30/Dec/2014:11:04:56] ENGINE Serving on http://0.0.0.0:8080
[30/Dec/2014:11:04:56] ENGINE Bus STARTED
But nothing else, no access logs, even after serving content.
I also tried
from cherrypy import wsgiserver
# Instead of the cherrypy.* calls
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8080), app)
server.start()
but it will print the same as above, but no access logs. Could not find any further documentation on logging and BottlePy integration.
The app you're running is not native CherryPy one, and grafting basically bypasses most of CP's internals, most likely including access logging.
Since you don't use any CherryPy's features besides basic WSGI publishing, you may be better off using one of the more serving-oriented (and more recent) solutions like uWSGI, Gunicorn or nginx/Apache+plugins.
You need to set log.screen to True to enable both error and access logs.
See (old) docs: https://cherrypy.readthedocs.org/en/3.3.0/refman/_cplogging.html

Categories

Resources