I want to create a very simple python web app. I don't need Django or any other web framwwork like that. Isn't there a simpler way to create a web app in python?
Thanks
If you don't need Django, try web.py
http://webpy.org/
import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name:
name = 'world'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
Sure! For example,
print 'Content-Type: text/plain'
print ''
print 'Hello, world!'
this is a web app -- if you save it into a file in an appropriate directory of a machine running a web server and set the server's configuration properly (depending on the server); the article I pointed to specifically shows how to deploy this web app to Google App Engine, but just about any web server can serve CGI apps, and this is a simple example thereof.
Of course, CGI has its limits, and you can use more sophisticated approaches (still short of a framework!) such as WSGI (also universally supported, if nothing else because it can run on top of CGI -- but in most cases you can also deploy it in more advanced ways) and possibly some of the many excellent utility components you can deploy with WSGI to save you work in coding certain parts of your apps.
WSGI is probably what you are looking for. Though there are several lightweight python web frameworks around which are less monolithic than django.
The truth is that you do need a framework of some sort even if it's extremely minimal. You can use WSGI as a base and at least you're doing a little better. Python is a very powerful, very unspecific programming language so if you decide to do it without a framework you're going to have to rewrite huge amounts of code that you may be taking for granted.
If you do decide to go with something other than Django try this list and maybe you'll find something simple enough that you'll feel good about it. :)
first we have to install the package.
In terminal:
>>> pip install PySimpleGUI
Then go on type in this code...
# Code
import PySimpleGUI as sg
sg.theme('add_your_bgcoloor_here') layout = [[sg.Text('This is for the text')],
[sg.InputText('This is to input the texts')],
[sg.InputCombo(['Option 1', 'Option 2', 'Option 3'])
[sg.Radio('Checkbox', 1)],
[sg.Spin([x for x in range(1, 100)], initial_value=1)],
[sg.Button('go']]
# creating our window window = sg.Window('Window, layout)
# defining the events and the value in the layout using while True statement while True:
event, values = window.read()
# defining our button 'go' (sg.Button('go'))
if event == 'go':
break window.close()
Yep WSGI...
def hello_wsgi(environ, start_response):
start_response('200 OK', [('content-type', 'text/html')])
return ['Hello world!']
If you want to abstract this in terms of request/response to get a little further away from http try webob.
from webob import Request, Response
def hello_wsgi(environ, start_response):
request = Request(environ)
#do something with the request
#return a response
return Response("Hello World!")(environ, start_response)
I use bottle all the time as a minimal web framework.
It is very simple to use.
as a minimum example - taken from the web site :
from bottle import route, run
#route('/hello/:name')
def index(name='World'):
return '<b>Hello %s!</b>' % name
run(host='localhost', port=8080)
you simply associate url (route) to functions. This one even get an optional argument.
It has an optional light templating language, and you can tweak it a lot for our needs. Very powerful.
It is also very easy to instal - as it comes as a single file, standing along your app, and is pure compliant python. It is also very easy to debug, with a nice autoreload on modif while in development mode.
As a final advantages, it runs smoothly under pypy - thus providing a speed boost over other frameworks.
Now a days it is better to use PhusionPassenger Standalone or with NGINX using same technique as PHP by proxy passing it to FastCGI in case of PHP and WSGI for Python.
The URL and all explanation for Passenger can be found: Here
All information about Python running on NGINX over FastCGI, uWSGI or Passenger
About frameworks that wrap Python for easier Web development I do recommend Django if it is a larger application and once you get the hang of it Django isn't that hard actually.
Good Luck!
You can try Appier (https://github.com/hivesolutions/appier). Here's a sample app:
import appier
class HelloApp(appier.App):
#appier.route("/", "GET")
def hello(self):
return "Hello World"
HelloApp().serve()
And here's how you run it:
pip install appier
python hello.py
Disclaimer: This framework is part of the open-source portfolio of my company. We built the framework to make the code for our consulting work as simple and clean as possible (to improve our efficiency). The project is very active, as we use the framework all the time, however, the caveat is that we've only started talking about it publicly recently, so there's no community around it yet. However, for that very reason, we're very open to cooperating closely with early bird developers in improving our documentation and adding new features.
Related
POOL = redis.ConnectionPool(host='localhost', port=6379, db=0)
app = Flask(__name__)
#app.route('/get_cohort_curve/', methods=['GET'])```
def get_cohort_curve():
curve = str(request.args.get('curve'))
cohort = str(request.args.get('cohort'))
key = curve+cohort
return get_from_redis(key)
def get_from_redis(key):
try:
my_server = redis.Redis(connection_pool=POOL)
return json.dumps(my_server.get(key))
except Exception, e:
logging.error(e)
app.run()
I need to write unit-tests for this.
How do I test just the route, i.e. a get request goes to the right place?
Do I need to create and destroy instances of the app in the test for each function?
Do I need to create a mock redis connection?
If you are interested in running something in Flask, you could create a virtual environment and test the whole shebang, but in my opinion that is THE HARDEST way to do it.
When I built my site installing Redis locally, setting the port and then depositing some data inside it with an appropriate key was essential. I did all of my development in iPython (jupyter) notebooks so that I could test the functions and interactions with Redis before adding the confounding layer of Flask.
Then you set up a flawless template, solid HTML around it and CSS to style the site. If it works without data as an html page, then you move on to the python part of Flask.
Solidify the Flask directories. Make sure that you house them in a virtual environment so that you can call them from your browser and it will treat your virtual environment as a server.
You create your app.py application. I created each one of the page functions one at a time. tested to see that it was properly pushing the variables to post on the page and calling the right template. After you get on up and running right, with photos and data, then at the next page's template, using #app.route
Take if very slow, one piece at a time with debugging on so that you can see where when and how you are going wrong. You will only get the site to run with redis server on and your virtual environment running.
Then you will have to shut down the VE to edit and reboot to test. At first it is awful, but over time it becomes rote.
EDIT :
If you really want to test just the route, then make an app.py with just the #app.route definition and return just the page (the template you are calling). You can break testing into pieces as small as you like, but you have to be sure that the quanta you pick are executable as either a python script in a notebook or commandline execution or as a compact functional self-contained website....unless you use the package I mentioned in the comment: Flask Unit Testing Applications
And you need to create REAL Redis connections or you will error out.
I'm trying to create a simple REST Web Service using technology WSME reported here:
https://pypi.python.org/pypi/WSME
It's not clear, however, how to proceed. I have successfully installed the package WSME.0.6.4 but I don't understand how to proceed.
On the above link we can see some python code. If I wanted to test the code what should I do? I have to create a .py file? Where this file should be saved? Are there services to be started?
The documentation is not clear: it says "With this published at the / ws path of your application". What application? Do I need to install a Web Server?
Thanks.
You could use a full blown web server to run your application . For example Apache with mod_wsgi or uWSGI , but it is not always necessary .
Also you should choose a web framework to work with .
According WSME doc's it has support for Flask microframework out of the box , which is simple enough to start with .
To get started create a file with the following source code :
from wsgiref.simple_server import make_server
from wsme import WSRoot, expose
class MyService(WSRoot):
#expose(unicode, unicode)
def hello(self, who=u'World'):
return u"Hello {0} !".format(who)
ws = MyService(protocols=['restjson', 'restxml'])
application = ws.wsgiapp()
httpd = make_server('localhost', 8000, application)
httpd.serve_forever()
Run this file and point your web browser to http://127.0.0.1:8000/hello.xml?who=John
you should get <result>Hello John !</result> in response.
In this example we have used python's built in webserver which is a good choice when you need to test something out quickly .
For addition i suggest reading How python web frameworks and WSGI fit together
I have written a web API in BaseHTTPServer. It is meant to be used only on localhost. It returns JSON objects on GET/POST operations.
http://localhost:8888/operation?param
and code is like
def do_GET(self):
if self.path=="operation":
self.wfile.write("output")
But I am worried about keep-alive mechanisms (read: a webserver that can respawn workers), lack of multi-threading, and PITA-ful maintenance.
And like I said, I am looking at the development and deployment issues for choosing this web framework.
Development
The web interface is currently 250 lines and has very simple features. I am looking for something that lends itself well to clean maintenance and deployment. I dont want the framework's MVC, ORM, templating and other features messing my learning curve. UrL patterns that redirect to appropriate module is nice.
Deployment
It should deploy on a mature server with a WSGI module with minimum fuss. And such a setup has hot-deploy (for want of a better word), installing a new application or updating the code means copying the files to the www-root in the filesystem.
CherryPy and Flask seem interesting. Django and Web2Py seem too comprehensive.
The recommended way of deploying wsgi is as a long-running-process, either embedded or daeomonized, and not as a cgi script. Either way, its going to be a little different than just uploading files like in php, restarting the server/process by touching the config file is normally the closest you get to "hot-deployment" using wsgi.
Needless to say, the framework itself does not impose any kind of deployment restraints if it is wsgi compliant. Take your pick depending on your needs: apache+modwsgi, gunicorn, cherry.py, paste. None of them offer "hot-deployment" (afaik), you will still need to create a wsgi script and reload the processes. The filesystem layout is normally of no concern and that's good. You don't usually get autoreload either. I know werkzeug and cherry.py do, and werkzeug offers some really cool debugging tools too. Please note that tornado/werkzeug* itself offers an autoreload option, but is actually considered for development and not deployment, and not compatible with the wsgi module.
But no matter how painful or painless the deployment is, it is recommended to use something like fabric to automate your deployments, and setting up a wsgi web server isnt that that hard.
Choice of the framework itself is kind of tricky, and depends on what level you want to work in. Tornado, werkzeug are popular low level frameworks, (but also include higher level tools, and many are frameworks+webserver), but you could also work with webob directly and just plugin whatever else you need.
You have the microframeworks like flask or bottle, then the lightweight frameworks, like web2.py, or maybe pyramid (the lines on how heavy a framework are kind of blurry).
Then you have the "full-stack" django, grok, turbogears, etc...
And then you have zope, which has been on a diet but still very heavy.
Note that you can pretty much do anything with all of them (just depends how much you want to bend them), and in many cases you can swap components rather easily. I'd start try out a microframework like bottle or maybe flask (you don't have to use ORM's or templating, but are easily available once you do), but also take a look at webob.
*comment: added werkzeug to the not really autoreload camp.
For what you describe, id go with: Tornado Web Server
This is the hello world:
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(8888)
tornado.ioloop.IOLoop.instance().start()
It's highly scalable, and I think it may take you 10 minutes to set it up with your code.
How to convert the web site develpoed in django, python into desktop application.
I am new to python and django can you please help me out
Thanks in Advance
I think you should just create an application that connects to the webserver. There is a good answer to getting RESTful API calls into your django application. This means you'd basically just be creating a new front-end for your server.
Using django-rest-interface
It doesn't make sense to rewrite the entire django application as a desktop application. I mean, where do you want to store the data?
For starters, you'll have to replace the web UI with a desktop technology like Tk/Tcl.
If you do that, you may not want to use HTTP as the protocol between the client and the services.
Django is a web framework. If you're switching to a desktop, you'll have to forego Django.
I would try to replicate the Django application functionality with the PyQt toolkit.
You can in fact embed web content in PyQt applications, with the help of QtWebKit. I would post some potentially useful links, but apparently I have too low a reputation to post more than one :)
There are two places you can go to try to decouple the view and put it into a new desktop app. First you can use the existing controller and model and adapt a new view to that. Second, you can use only the existing model and build a new view and controller.
If you haven't adhered closely enough to the MVC principles that you can detach the model from the rest of the application, you can simply rewrite the entire thing. if you are forced to go this route, bail on django and http entirely (as duffymo suggests above).
You have to also evaluate these solutions based upon performance requirements and "heaviness" of the services. If you have stringent performance requirements then relying on the HTTP layer just gets in the way, and providing a simple API into your model is the way to go.
There are clearly a lot of possibly solutions but this is the approach I would take to deciding what the appropriate one is...
It is possible to convert a django application to a desktop app with pywebview with some line of codes. Frist create a python file gui.py in directory where manage.py exists. install pywebview through pip, the write the code in gui.py
import os
import sys
import time
from threading import Thread
import webview
def start_webview():
window = webview.create_window('Hello world', 'http://localhost:8000/', confirm_close=True, width=900, height=600)
webview.start()
window.closed = os._exit(0)
def start_startdjango():
if sys.platform in ['win32', 'win64']:
os.system("python manage.py runserver {}:{}".format('127.0.0.1', '8000'))
# time.sleep(10)
else:
os.system("python3 manage.py runserver {}:{}".format('127.0.0.1', '8000'))
# time.sleep(10)
if __name__ == '__main__':
Thread(target=start_startdjango).start()
start_webview()
then run gui.py with the command python gui.py. IT will create a window like desktop app
There's a project called Camelot which seems to try to combine Django-like features on the desktop using PyQt. Haven't tried it though.
I am thinking about a similar Problem.
Would it be enough to habe a minimal PyQt Gui that enables you to present the djando-website from localhost (get rid of TCP/HTTPS on loop interface somehow) via QtWebkit?
All you seem to need is to have a minimal Python-Broser, that surfs the build in Webserver (and i guess you could even call Django directly for the html-payload without going over the HTTP/TCP layers).
I have django manage.py runserver in .bat file and a localhost bookmark bar in a browser and whola a django-desktop-app. Or make your own browser that opens localhost. Creating a web-browser with Python and PyQT
I'm on an app engine project where I'd like to put in a link to a Javascript test runner that I'd like to only exist when running the development server. I've made some experiments on a local shell with configuration loaded using the technique found in NoseGAE versus live on the 'App Engine Console' [1] and it looks to me like a distinction btw real instance and dev server is the presence of the module google.appengine.tools. Which lead me to this utility function:
def is_dev():
"""
Tells us if we're running under the development server or not.
:return:
``True`` if the code is running under the development server.
"""
try:
from google.appengine import tools
return True
except ImportError:
return False
The question (finally!) would be: is this a bad idea? And in that case, can anyone suggest a better approach?
[1] http://con.appspot.com/console/ (try it! very handy indeed)
The standard way to test for the development server is as follows:
DEBUG = os.environ['SERVER_SOFTWARE'].startswith("Dev")
Relying on the existence or nonexistence of a particular module - especially an undocumented one - is probably a bad idea.
I'd recommend doing it this way:
import os
def onDevServer():
return os.environ['SERVER_SOFTWARE'].find('Development') >= 0
This looks at the environment you're running in, and returns true if you're running on the development server. However, its a much cleaner way than checking an import, in my opinion.
I'm not a google app developer, but I wouldn't make this 100% dynamic, but also look at a value from a config file. I'm pretty sure you will be running into the problem, that you want to see this console on the prod system (google servers) or run your local version without the dev code (for testing).
To sum it up: Such a logic is fine for small stuff, like adding a debug link, but provide a way to overwrite it (e.g. by a configuration value)