How use Django with Tornado web server? - ajax

How do I use Django with the Tornado web server?

it's very simple ( especially with django 1.4) .
1 - just build your django project( and apps ) and make sure it works fine.
2- create a new python file at the root folder ( same dir where you used django-admin.py startproject)
3- then copy the code below , edit the os.environ['DJANGO_SETTINGS_MODULE'] line, and paste it in that new .py file.
import os
import tornado.httpserver
import tornado.ioloop
import tornado.wsgi
import sys
import django.core.handlers.wsgi
#sys.path.append('/home/lawgon/') # path to your project ( if you have it in another dir).
def main():
os.environ['DJANGO_SETTINGS_MODULE'] = 'myProject.settings' # path to your settings module
application = django.core.handlers.wsgi.WSGIHandler()
container = tornado.wsgi.WSGIContainer(application)
http_server = tornado.httpserver.HTTPServer(container)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
Django 1.6+ it should be like this:
import os
import tornado.httpserver
import tornado.ioloop
import tornado.wsgi
from django.core.wsgi import get_wsgi_application
def main():
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' # path to your settings module
application = get_wsgi_application()
container = tornado.wsgi.WSGIContainer(application)
http_server = tornado.httpserver.HTTPServer(container)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()

UPDATE:
I created a minimal working demo which shows how to use the Tornado web server to run nicely with django:
https://github.com/tamasgal/django-tornado
ORIGINAL POST:
Just a remark: The WSGI application workflow has been changed from 1.6 to 1.7. You have to replace the import
import django.core.handlers.wsgi
with
from django.core.wsgi import get_wsgi_application
and change the application initialisation from
application = django.core.handlers.wsgi.WSGIHandler()
to
application = get_wsgi_application()
This is the modified code from the Moayyad Yaghi's answer:
import os
import tornado.httpserver
import tornado.ioloop
import tornado.wsgi
import sys
import django.core.handlers.wsgi
from django.core.wsgi import get_wsgi_application
#sys.path.append('/home/lawgon/') # path to your project ( if you have it in another dir).
def main():
os.environ['DJANGO_SETTINGS_MODULE'] = 'myProject.settings' # path to your settings module
application = django.core.handlers.wsgi.WSGIHandler()
application = get_wsgi_application()
container = tornado.wsgi.WSGIContainer(application)
http_server = tornado.httpserver.HTTPServer(container)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()

There's a project called tornado-proxy that would help you. But I would like to recommend that you use Nginx. In the Nginx config you could now use proxy_pass to direct your calls like this:
location /comet {
proxy_pass http://localhost:8081;
}
location / {
proxy_pass http://localhost:8080;
}

In real world you would connect Django and some production-ready webserver with WSGI. This demo shows how you can run Tornado (and it's webserver) and Django side by side from one python module serving different URL prefixes: https://github.com/bdarnell/django-tornado-demo.
Tornado would block on serving any request directed to Django, though.

Related

How to copy to clipboard from browser using python 3.10.4 and Ubuntu 22.04?

I have the following code that is automating a process in the browser.
At the line pt.click(clicks=3) I can get the text selected in the input box (Chrome). At the line pc.copy() I should copy this text and send it to the variable self.message to be processed. This step is not working.
There are a lot of documents and tutorials on how to do that on Windows and Mac, not in Ubuntu, specially in Ubuntu 22.04.
I am using OS Ubuntu 22.04 and Python 3.10.4.
What am I missing?
from turtle import right
import cv2 as cv
from time import sleep
# Waiting time
print('Waiting 2s')
sleep(2)
import pyautogui as pt
import paperclip as pc
from tkinter import ttk
....
def nav_message(self):
try:
clipPicCenter = pt.locateCenterOnScreen('./clip_pic.png', confidence=0.7)
# print('LocateCenter clip_pic', clipPicCenter)
pt.moveTo(clipPicCenter[0]+48, clipPicCenter[1]-60, duration=self.speed)
pt.click(clicks=3)
sleep(.9)
self.message = pc.copy() //Out PUT - Pyperclip do not have the method copy()
print(self.message)
# pt.click(button='right', clicks=1)
# pos = pt.position()
# pt.moveTo(pos[0]+20, pos[1]-300, duration=self.speed)
# txt = pt.click()
# print(txt)
# self.nav_input_box()
# pt.write(txt)
# txt = pt.hotkey("ctrl", "c") # copy the text (simulating key strokes)
# pt.click(button=right)
except Exception as e:
print ('Exception (nav_green_dot): ', e)
you can use this to copy something to your clipboard
import pyperclip
s1 = "Hello world"
pyperclip.copy(s1)
s2 = pyperclip.paste()
print(s2)
Line 9 you import paperclip as pc. You need to import pyperclip as pc (Note that it starts with py and not pa). The 2 are spelled similar, but your code imports the paperclip library for Django instead of the pyperclip library for managing the clipboard. Heres a codeblock with your fixed imports:
from turtle import right
import cv2 as cv
from time import sleep
# Waiting time
print('Waiting 2s')
sleep(2)
import pyautogui as pt
# this used to be "paperclip"
# "pyperclip" is what you need to import
import pyperclip as pc
from tkinter import ttk

How to get rid of the error of keep_alive?

from keep_alive import keep_alive
with error
Import "keep_alive" could not be resolved
same directory, have the keep alive file
anyone help me?
basically how do do keep alive
from flask import Flask
from threading import Thread
app = Flask('')
app.route('/')
def main():
return "Bot is online."
def run():
app.run(host = "0.0.0.0", port = 8000)
def keep_alive():
server = Thread(target = run)
server.start()
This is what the keep_alive file contains, and name it like host.py or something. If you are naming it host.py then in your main.py you should add this too.
from host import keep_alive
keep_alive() #added at the bottom after all commands

How To Use Django-Crontab in Ec2 ubuntu

cronjob
*/30 * * * * /home/ubuntu/web-coin-crawler/venv/bin/python3 /home/ubuntu/web-coin-crawler/webcoincrawler/cron.crontab
cron.py, crontab() Function that crawls on two sites. Save to Django orm as save().
import json
import collections
import crawl_coinmarketcal as coinmarketcal
import crawl_coinscalendar as coinscalendar
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
import django
import datetime
django.setup()
from crawled_data.models import BlogData
def preprocessingDict(dic: dict):
coin_dict = collections.defaultdict(dict)
for key, value in dic.items():
if value['symbol'] in coin_dict[value['date']]:
coin_dict[value['date']][value['symbol']].append([key, value['title'], value['name']])
else:
coin_dict[value['date']][value['symbol']] = [[key, value['title'], value['name']]]
return coin_dict
def crontab():
result = dict()
urls = coinmarketcal.get_urls()
for url in urls:
coinmarketcal.do_crawl(url, result)
urls = coinscalendar.get_urls()
for url in urls:
coinscalendar.do_crawl(url, result)
BlogData(title="COIN_DATA", content=json.dumps(preprocessingDict(result.copy()))).save()
I checked that the cron tab runs every 30 minutes.
However, no data was stored in Django orm.
I changed the Python file itself to run and it was solved.
cron.crontab -> cron

flask server running in virtual box is not accessible from the windows host

I have tried running it from host='0.0.0.0' and it is still inaccessible. I can ping my windows machine ip 192.168.1.109 from my virtualmachine, but I can not ping my Ubuntu VirtualMachine ip from ifconfig 10.0.2.15 from my windows side. I am using virtualbox if that helps.
run.py
#!flask/bin/python
from app import app
app.run(host='0.0.0.0',port=5000, debug=True)
init.py
import os
from flask import Flask
from flask.json import JSONEncoder
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_mail import Mail
from flask_babel import Babel, lazy_gettext
from config import basedir, ADMINS, MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, \
MAIL_PASSWORD
from .momentjs import momentjs
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
lm.login_message = lazy_gettext('Please log in to access this page.')
mail = Mail(app)
babel = Babel(app)
class CustomJSONEncoder(JSONEncoder):
"""This class adds support for lazy translation texts to Flask's
JSON encoder. This is necessary when flashing translated texts."""
def default(self, obj):
from speaklater import is_lazy_string
if is_lazy_string(obj):
try:
return unicode(obj) # python 2
except NameError:
return str(obj) # python 3
return super(CustomJSONEncoder, self).default(obj)
app.json_encoder = CustomJSONEncoder
if not app.debug and MAIL_SERVER != '':
import logging
from logging.handlers import SMTPHandler
credentials = None
if MAIL_USERNAME or MAIL_PASSWORD:
credentials = (MAIL_USERNAME, MAIL_PASSWORD)
mail_handler = SMTPHandler((MAIL_SERVER, MAIL_PORT),
'no-reply#' + MAIL_SERVER, ADMINS,
'microblog failure', credentials)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
if not app.debug and os.environ.get('HEROKU') is None:
import logging
from logging.handlers import RotatingFileHandler
file_handler = RotatingFileHandler('tmp/microblog.log', 'a',
1 * 1024 * 1024, 10)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)
app.logger.info('microblog startup')
if os.environ.get('HEROKU') is not None:
import logging
stream_handler = logging.StreamHandler()
app.logger.addHandler(stream_handler)
app.logger.setLevel(logging.INFO)
app.logger.info('microblog startup')
app.jinja_env.globals['momentjs'] = momentjs
from app import views, models
It worked for me when I changed this line in the main
app.run()
to
app.run(host='192.168.163.128', port=5000)

from Gui import * in python 3?

I'm trying this:
import os, sys
from Gui import *
import Image as PIL
import ImageTk
class ImageBrowser(Gui):
def __init__(self):
Gui.__init__(self)
self.button = self.bu(command=self.quit, relief=FLAT)
def image_loop(self, dirname='.'):
files = os.listdir(dirname)
for file in files:
try:
self.show_image(file)
print (file)
self.mainloop()
except IOError:
continue
except:
break
def show_image(self, filename):
image = PIL.open(filename)
self.tkpi = ImageTk.PhotoImage(image)
self.button.config(image=self.tkpi)
def main(script, dirname='.'):
g = ImageBrowser()
g.image_loop(dirname)
if __name__ == '__main__':
main(*sys.argv)
I'm getting an error that says:
from Gui import *
ImportError: No module named Gui
I'm assuming "from Gui import *" doesn't work in python 3, does anyone know how to do this in python 3? Thank you so much (:
If you are talking about the Gui module that comes with Swampy, then
in order to use Gui with Python3, you'll need to install the Python3 version of Swampy.

Resources