Django as middleware in a tornado app - python

I am trying to run tornadio (socket.io for python) to work with django. Is there are way to do something like this in tornado (running django as middleware), or can I access tornadio from within django (uncommenting the second application definition routes straight to django):
#!/usr/bin/env python
import os
import tornado.httpserver
import tornado.ioloop
import tornado.wsgi
import sys
sys.path.append('..')
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import django.core.handlers.wsgi
wsgi = django.core.handlers.wsgi.WSGIHandler()
django_container = tornado.wsgi.WSGIContainer(wsgi)
application = tornado.web.Application([
(r"/", MainHandler),
django_container
])
# application = django_container
tornado.httpserver.HTTPServer(application).listen(8888)
tornado.ioloop.IOLoop.instance().start()

I would look at using this project to help:
https://github.com/koblas/django-on-tornado
It an integration of tornado and django allowing you to do this:
python manage.py runtornado --reload 8888
Included is a sample chat service built using django and tornado.

Related

ModuleNotFoundError: No module named '__main__.web_app'; '__main__' is not a package while importing package from sub folder

I'm getting above error while running my app. I want to import app from web_app/init.py into run.py file to run on gevent. My project structure is like:
myapp
|---config.ini
|---run.py
|---web_app
|----__init__.py
run.py
from gevent.pywsgi import WSGIServer
import configparser
from .web_app import app
# from web_app.__init__ import app
config = configparser.ConfigParser()
config.read('C:/workspace/Python/myapp/config.ini')
PORT = config.get('SERVER', 'PORT')
PORT = int(PORT)
if __name__ == '__main__':
print('Serving on port ', PORT)
WSGIServer(('localhost', PORT), app).serve_forever()
__init.py
from flask import Flask
app = Flask(__name__)
app.config['APPLICATION_ROOT'] = '/myapp'
logger = log_configuration.get_logger(__name__)
def simple(env, resp):
resp(b'200 OK', [(b'Content-Type', b'application/json')])
return [b'Hello Verimed User']
#app.route('/test', methods=['GET'])
def test():
return jsonify({'tasks': "task"})
If I keep run.py beside init then it's working fine. But I want to keep run.py outside web_app folder.
How to rosolve this. I tried all the way.
Have you tried it without the "." in front of "web_app"?
from web_app import app
You can find some more info in the following link: relative imports
I resolved above problem after added following code into the run.py.
import sys
sys.path.append('../web_app')
sys.path.insert(0,'./web_app')

Non-blocking tornado instance on Openshift?

I am trying to create tornado webserver and quick start made me standard project of tornado, but according to documentation this configuration is blocking.
I am new to non-blocking python.
I have this wsgi file that lies in root folder in my PAAS server
#!/usr/bin/env python
import os
import imp
import sys
#
# Below for testing only
#
if __name__ == '__main__':
ip = 'localhost'
port = 8051
zapp = imp.load_source('application', 'wsgi/application')
from wsgiref.simple_server import make_server
httpd = make_server(ip, port, zapp.application)
httpd.serve_forever()
This is main handler file
#!/usr/bin/env python
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
And Application folder contains this
# Put here yours handlers.
import tornado.wsgi
from . import handlers
handlers = [(r'/',MainHandler),]
application = tornado.wsgi.WSGIApplication(handlers, **settings)
In WSGI mode asynchronous methods are not supported
uses WSGI to deploy the python applications
Is it possible to configure python application on openshift to be fully non-blocking
Though i have seen project that seemed to work
If you are talking about OpenShift V2 (not V3 which uses Kubernetes/Docker), then you need to use the app.py file as described in:
http://blog.dscpl.com.au/2015/08/running-async-web-applications-under.html

How to deploy CherryPy on pythonanywhere.com

I have a python app developed on Flask. Everything works fine offline, I tried deploying on CherryPy successfully too. Now, I'm trying to deploy the same on www.pythonanywhere.com.
Here's the deploy.py I use for deploying the Flask app on CherryPy
from cherrypy import wsgiserver
from appname import app
def initiate():
app_list = wsgiserver.WSGIPathInfoDispatcher({'/appname': app})
server = wsgiserver.CherryPyWSGIServer( ('http://username.pythonanywhere.com/'), app_list)
try:
server.start()
except KeyboardInterrupt:
server.stop()
print "Server initiated..."
initiate()
print "Ended"
I created a "manual configuration" app on pythonanywhere.com.
Here's the configuration file (username_pythonanywhere_com_wsgi.py):
import sys
path = '/home/username/appname'
if path not in sys.path:
sys.path.append(path)
import deploy
deploy.initiate()
Now I'm pretty sure that it "almost worked", because in the server logs I could see my "Server initiated..." message.
2013-09-27 09:57:16 +0000 username.pythonanywhere.com - *** Operational MODE: single process ***
Server initiated...
Now the problem, when I try to view my app username.pyhtonanywhere.com/about, it times out.
This I believe is caused due to incorrect port given while starting the CherryPy server (in deploy.py).
Could anyone please tell how I can properly initiate the CherryPy server?
Joe Doherty is right. You want something more like this in you wsgi file:
import sys
sys.path = [ <path to your web app> ] + sys.path
from cherrypy._cpwsgi import CPWSGIApp
from cherrypy._cptree import Application
from <your_web_app> import <your web app class>
config_path = '<path to your cherrypy config>'
application = CPWSGIApp(
Application(<your web app class>(), '', config = config_path)
I stuck everything that should be based on your particular app in <>s.

Integrating fanstatic with tornado web?

I'm attempting to integrate fanstatic.org with tornadoweb and was curious if anyone has any prior knowledge or any code that may reflect how this is done? I've been reading the documentation and i believe it can be done since tornado does provide a wsgi interface.
thanks
import tornado.wsgi
from fanstatic import Fanstatic
from your_tornado_app import MainHandler # tornado.web.RequestHandler
app = tornado.wsgi.WSGIApplication([
(r"/", MainHandler),
])
app = Fantastic(app)
if __name__ == '__main__':
from wsgiref.simple_server import make_server
server = make_server('127.0.0.1', 8080, app)
server.serve_forever()

How do you run the Tornado web server locally?

Is it possible to run Tornado such that it listens to a local port (e.g. localhost:8000). I can't seem to find any documentation explaining how to do this.
Add an address argument to Application.listen() or HTTPServer.listen().
It's documented here (Application.listen) and here (TCPServer.listen).
For example:
application = tornado.web.Application([
(r'/blah', BlahHandler),
], **settings)
# Create an HTTP server listening on localhost, port 8080.
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8080, address='127.0.0.1')
In the documetaion they mention to run on the specific port like
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8000)
tornado.ioloop.IOLoop.instance().start()
You will get more help from http://www.tornadoweb.org/documentation/overview.html and http://www.tornadoweb.org/documentation/index.html
Once you've defined an application (like in the other answers) in a file (for example server.py), you simply save and run that file.
python server.py
If you want to daemonize tornado - use supervisord. If you want to access tornado on address like http://mylocal.dev/ - you should look at nginx and use it like reverse proxy. And on specific port it can be binded like in Lafada's answer.

Categories

Resources