As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I've been using python for years, but I have little experience with python web programming. I'd like to create a very simple web service that exposes some functionality from an existing python script for use within my company. It will likely return the results in csv. What's the quickest way to get something up? If it affects your suggestion, I will likely be adding more functionality to this, down the road.
Have a look at werkzeug. Werkzeug started as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility modules. It includes a powerful debugger, full featured request and response objects, HTTP utilities to handle entity tags, cache control headers, HTTP dates, cookie handling, file uploads, a powerful URL routing system and a bunch of community contributed addon modules.
It includes lots of cool tools to work with http and has the advantage that you can use it with wsgi in different environments (cgi, fcgi, apache/mod_wsgi or with a plain simple python server for debugging).
web.py is probably the simplest web framework out there. "Bare" CGI is simpler, but you're completely on your own when it comes to making a service that actually does something.
"Hello, World!" according to web.py isn't much longer than an bare CGI version, but it adds URL mapping, HTTP command distinction, and query parameter parsing for free:
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()
The simplest way to get a Python script online is to use CGI:
#!/usr/bin/python
print "Content-type: text/html"
print
print "<p>Hello world.</p>"
Put that code in a script that lives in your web server CGI directory, make it executable, and run it. The cgi module has a number of useful utilities when you need to accept parameters from the user.
Raw CGI is kind of a pain, Django is kind of heavyweight. There are a number of simpler, lighter frameworks about, e.g. CherryPy. It's worth looking around a bit.
Look at the WSGI reference implementation. You already have it in your Python libraries. It's quite simple.
If you mean with "Web Service" something accessed by other Programms SimpleXMLRPCServer might be right for you. It is included with every Python install since Version 2.2.
For Simple human accessible things I usually use Pythons SimpleHTTPServer which also comes with every install. Obviously you also could access SimpleHTTPServer by client programs.
Life is simple if you get a good web framework. Web services in Django are easy. Define your model, write view functions that return your CSV documents. Skip the templates.
If you mean "web service" in SOAP/WSDL sense, you might want to look at Generating a WSDL using Python and SOAPpy
maybe Twisted
http://twistedmatrix.com/trac/
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
How to create simple web site with Python?
I mean really simple, f.ex, you see text "Hello World", and there are button "submit", which onClick will show AJAX box "submit successful".
I want to start develop some stuff with Python, and I don't know where to start.
I was hoping more elaborate answers would be given to this question, since it's a sensitive subject. Python web developing is split across lots of frameworks, each with its ups and downs and every developer using a different one. This is quite unfortunate. What you should know:
Use WSGI. Don't use anything else, WSGI is the latest standard in Python web developing;
Don't develop directly on top of WSGI, unless you really have to (not even for a hello world app);
Use a framework that best suits your needs:
I played with Werkzeug (which is not really a platform, they call it a toolkit) because it's really simple yet powerful. It lets you work on the WSGI level (also helps you understand how WSGI works) while providing really useful features and helpers. On the Werkzeug website you will also find useful tutorials and things like that.
Probably the most popular framework is Django. Never used it, but maybe there's a reason for why it is so popular.
In conclusion, use whatever is closest to your heart.
You can write a web site with Python in which the web server is implemented in Python, or in which Python is called from some other web server. If you do not already have a web server set up, the first option is easier. The Python library includes a fully functional web server, all you have to is add a couple of methods to respond to requests.
For a complete example of a web site using this simple technique, see Making a simple web server in Python
This technique may or may not serve you well for developing commercial, production web sites, but it's the simplest way from P(ython) to W(ebsite).
Why don't you try out the Google AppEngine stuff? They give you a local environment (that runs on your local system) for developing the application. They have nice, easy intro material for getting the site up and running - your "hello, world" example will be trivial to implement.
From there on, you can either go with some other framework (using what you have learnt, as the vanilla AppEngine stuff is pretty standard for simple python web frameworks) or carry on with the other stuff Google provides (like hosting your app for you...)
As Felix suggested, definitely use WSGI (mod_wsgi) as your gateway interface. It is the modern way of doing business and the other major contendor, mod_python, is no longer being maintained.
Django is a great choice if you want a full-fledged production-quality framework but it also comes at the cost of having a lot of overhead and a pretty steep learning curve.
My suggestion is: Tornado!
I have found that Tornado makes it very easy to get up and running quickly. To illustrate here is the "Hello, World" from the Tornado documentation:
import tornado.httpserver
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__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
In my opinion that speaks for itself.
Edit: It's important to note that you don't have to use the web server that comes with Tornado. It plugs very easily into WSGI to run with whatever server you already have going.
Best of luck in your search!
You can take this course offered FREE on udacity Web Development using Python.
This is great course and teaches from scratch using GAE. At the end of the course you would have a full fledged blog of yours on web developed by you in python.
P.S one of the instructor is Steve Huffman founder of Reddit.
I think you should start with some kind of Python web framework. For me Web2Py is both easy and powerful. Of course you can create your pages using CGI: no framework required, but for more complicated sites it is not practical.
I'm looking for a suitable cross-platform web framework (if that's the proper term). I need something that doesn't rely on knowing the server's address or the absolute path to the files. Ideally it would come with a (development) server and be widely supported.
I've already tried PHP, Django and web2py. Django had an admin panel, required too much information (like server's address or ip) and felt unpleasant to work with; PHP had chown and chmod conflicts with the server (the code couldn't access uploaded files or vice versa) and couldn't handle urls properly; web2py crashed upon compiling and the manual didn't cover that -- not to mention it required using the admin panel. Python is probably the way to go, but even the amount of different web frameworks and distributions for Python is too much for me to install and test individually.
What I need is a simple and effective cross-platform web development language that works pretty much anywhere. No useless admin panels, no fancy user interfaces, no databases (necessarily), no restrictions like users/access/levels and certainly no "Web 2.0" crap (for I hate that retronym). Just an all-powerful file and request parser.
I'm used to programming in C and other low level languages, so difficulty is not a problem.
This question is based on a complete failure to understand any of the tools you have apparently "investigated", or indeed web serving generally.
Django has an admin panel? Well, don't use it if you don't want to. There's no configuration that needs to be done there, it's for managing your data if you want.
PHP has chown problems? PHP is a language, not a framework. If you try and run something with it, you'll need to set permissions appropriately. This would be the case whatever language you use.
You want something that doesn't need to know its address or where its files are? What does that even mean? If you are setting up a webserver, it needs to know what address to respond to. Then it needs to know what code to run in response to a request. Without configuring somewhere the address and the path to the files, nothing can ever happen.
In web2py you do not need to use the admin interface. It is optional.
Here is how you create a simple app from zero:
wget http://web2py.com/examples/static/web2py_src.zip
unzip web2py_src.zip
cd web2py/applications
mkdir myapp
cp -r ../welcome/* ./
Optional Edit your app
emacs controllers/default.py
emacs models/db.py
emacs views/default/index.html
...
(you can delete everything in there you do not need).
Now run web2py and try it out
cd ../..
python web2py.py -i 127.0.0.1 -p 8000 -a chooseapassword &
wget http://127.0.0.1:8000/myapp/default/index.html
When you edit controller/default.py you have a controller for example
def index():
the_input = request.vars # this is parsed from URL
return dict(a=3,b=5,c="hello")
You can return a dict (will be parsed by the view with same name as action) or a string (the actual page content). For example:
def index():
name = request.vars.name or 'anonymous'
return "hello "+name
and call
wget http://127.0.0.1:8000/myapp/default/index?name=Max
returns
'hello Max'
/myapp/default/index?name=Max calls the function index, of the controller default.py of the application in folder applications/myapp/ and passes name=Max into request.vars.name='Max'.
I think you need to be more specific about what you want to achieve, and what kind of product(s) you want to develop. A "no setup required" product may come with tons of auto-configuration bloat, while a framework requiring a small setup file could be set up in minutes, too, with much more simplicity in the long run. There is also always going to be some security and access rights to be taken into consideration, simply because the web is an open place.
Also, a framework supporting Web 2.0ish things doesn't have to be automatically a bad framework. Don't throw away good options because they also do things you don't like or need, as long as they allow you to work without them.
PHP had chown and chmod conflicts with the server (the code couldn't access uploaded files or vice versa) and couldn't handle urls properly;
PHP is not a framework in itself, it's a programming language. I don't know which PHP-based framework or product you tried but all the problems you describe are solvable, and not unique to PHP. If you like the language, maybe give it another shot. Related SO questions:
What PHP framework would you choose for a new application and why?
What’s your ‘no framework’ PHP framework?
If you need something that runs everywhere (i.e. on as many servers as possible) PHP will naturally have to be your first choice, simply because it beats every other platform in terms of cheap hosting availability.
If I were you, I wouldn't limit my options that much at this point, though. I hear a lot of good things about Django, for example. Also, the Google App engine is an interesting, scalable platform to do web work with, supporting a number of languages.
Werkzeug:
import werkzeug
#werkzeug.Request.application
def app(request):
return werkzeug.Response("Hello, World!")
werkzeug.run_simple("0.0.0.0", 4000, app)
You can optionally use werkzeug URL routing (or your own, or anything from any other framework). You can use any ORM or template engine for Python you want (including those from other Python frameworks) etc.
Basically it's just Request and Response objects built around WSGI plus some utilities. There are more similar libraries available in Python (for example webob or CherryPy).
What I need is a simple and effective cross-platform web development language that works pretty much anywhere.
Have you tried HTML?
But seriously, I think Pekka is right when he says you need to specify and clarify what you want.
Most of the features you don't want are standard modules of a web app (user and role mgmt., data binding, persistence, interfaces).
We use any or a mix of the following depending on customer requirements: perl, PHP, Flash, Moonlight, JSP, JavaScript, Java, (D/X)HTML, zk.
I am python newbie but experienced PHP developer for 12 years but I have to admit that I migrated to python because of the bottle framework. I am African so you don't have to be extra smart to use it... Give it a try, you'll love it. Hey and it also runs on appspot with no config!
Install python
Download bottle.py (single file)
Create
#your file name : index.py
from bottle import route, run
#route('/')
def index():
return 'jambo kenya! hakuna matata na bottle. hehehe'
run()
Sit back, sip cocoa and smile :)
I'd say Ruby on Rails is what you're looking for. Works anywhere, and no configuration needed. You only have it installed, install the gems you need, and off you go.
I also use ColdFusion, which is totally multi-platform, but relies on the Administrator settings for DSN configuration and stuff.
TurboGears: Everything optional.
Give bottle a try. I use it for my simple no-frills webapps. It is very intuitive and easy to work with in my experience.
Here is some sample code, and it requires just bottle.py, no other dependencies.
from bottle import route, run
#route('/')
def index():
return 'Hello World!'
run(host='localhost', port=8080)
Just stumbled upon Quixote recently. Never used it though.
Use plain old ASP. IIS does not care where files are stored. All paths can be set relative from the virtual directory. That means you can include "/myproject/myfile.asp", whereas in PHP it's often done using relative paths. Global.asa then contains global configuration for the application. You hardly ever have to worry about relative paths in the code.
In PHP you'd have include(dirname(FILE) . '/../../myfile.php") which is of course fugly. The only 'solution' I found for this is making HTML files and then using SSI (server side includes).
The only downside to ASP is the availability, since it has to run on Windows. But ASP files just run, and there's not complex Linux configuration to worry about. The language VBScript is extremely simple, but you can also choose to write server side JavaScript, since you're familiar with C.
I think you need to focus on Restful web applications. Zend is a PHP based MVC framework.
I am very new to python and having to get into this stuff for a simple program to integrate with an ASP.NET application that I am building. The pseudo code is as follows.
Get two parameters from request. (A ASP.NET will be calling this url by POST and sending two parameters)
Internally execute some business logic and build some response.
Write the response back so that the ASP.NET app can proceed.
Step 2 and 3 are already in place and working too but not able to find a solution for Step 1 (I know it should be very simple and know how to do it in Java/.NET/PHP and RoR but not in Python and the online docs/tutorials are not helping my cause). I am running python on apache using mod_python.
Any help here is greatly appreciated. Thanks in advance
Vijay
Here is a good beginner's tutorial for mod_python.
As far as I understand your question you have a mod_python-based script and you want to read a POST parameter. Therefore you only have to use the form object which is automatically provided by mod_python:
myparameter = form.getfirst("name_of_the_post_parameter")
You can find the documentation over here.
Note that this solution is when your server is configured with PythonHandler mod_python.psp which will allow you to use "Python Server Pages" (special <% %> tags, automatically created variables like form, ...). If you're writing a normal mod_python handler, then it would look something like that:
from mod_python import util
def handler(req):
form = util.FieldStorage(req, keep_blank_values=1)
myparameter = form.getfirst("name_of_the_post_parameter")
...other stuff...
"I know it should be very simple and know how to do it in Java/.NET/PHP and RoR but not in Python"
Well, it's not simple in Python -- the language.
It is simple in many Python web frameworks.
Don't make the mistake of comparing Python (the language) with PHP (the web framework) or RoR (the web framework).
Python, like Java or VB or Ruby, is a programming language. Not a web framework.
To get stuff from Apache into Python you have three choices.
A CGI script. A dreadful choice.
mod_python. Not a great choice.
mod_wsgi. A much better choice.
If you're stuck with mod_python -- because this is homework, for instance -- you'll need to read a mod_python tutorial in addition to a python tutorial.
This, for example, seems to be what you're doing. http://www.modpython.org/live/current/doc-html/tut-pub.html
I'm pretty proficient in PHP, but want to try something new.
I'm also know a bit of Python, enough to do the basics of the basics, but haven't used in a web design type situation.
I've just written this, which works:
#!/usr/bin/python
def main():
print "Content-type: text/html"
print
print "<html><head>"
print "<title>Hello World from Python</title>"
print "</head><body>"
print "Hello World!"
print "</body></html>"
if __name__ == "__main__":
main()
Thing is, that this seems pretty cumbersome. Without using something huge like django, what's the best way to write scripts that can process get and post?
Your question was about basic CGI scripting, looking at your example, but it seems like everyone has chosen to answer it with "use my favorite framework". Let's try a different approach.
If you're looking for a direct replacement for what you wrote above (ie. CGI scripting), then you're probably looking for the cgi module. It's a part of the Python standard library. Complimentary functionality is available in urllib and urllib2. You might also be interested in BaseHTTPServer and SimpleHTTPServer, also part of the standard library.
Getting into more interesting territory, wsgiref gives you the basics of a WSGI interface, at which point you probably want to start thinking about more "frameworky" (is that a word?) things like web.py, Django, Pylons, CherryPy, etc, as others have mentioned.
As far as full frameworks go I believe Django is relatively small.
If you really want lightweight, though, check out web.py, CherryPy, Pylons and web2py.
I think the crowd favorite from the above is Pylons, but I am a Django man so I can't say much else.
For more on lightweight Python frameworks, check out this question.
There are a couple of web frameworks available in python, that will relieve you from most of the work
Django
Pylons (and the new TurboGears, based on it).
Web2py
CherryPy (and the old TurboGears, based on it)
I do not feel Django as "big" as you say; however, I think that Pylons and CherryPy may be a better answer to your question. CherryPy seems simpler,. but seems also a bit "passé", while Pylons is under active development.
For Pylons, there is also an interesting Pylons book, available online.
In Python, the way to produce a website is to use a framework. Most of the popular (and actively maintained/supported) frameworks have already been mentioned.
In general, I do not view Djano or Turbogears as "huge", I view them as "complete." Each will let you build a database backed, dynamic website. The preference for one over the other is more about style than it is about features.
Zope on the other hand, does feel "big". Zope is also "enterprise" class in terms of the features that are included out of the box. One very nice thing is that you can use the ZODB (Zope Object Database) without using the rest of Zope.
It would certainly help if we knew what kinds of websites you were interested in developing, as that might help to narrow the suggestions.
In web2py the previous code would be
in controller default.py:
def main():
return dict(message="Hello World")
in view default/main.html:
<html><head>
<title>Hello World from Python</title>
</head><body>
{{=message}}
</body></html>
nothing else, no installation, no configuration, you can edit the two files above directly on the web via the admin interface. web2py is based on wsgi but works also with cgi, mod_python, mod_proxy and fastcgi if mod_wsgi is not available.
I really love django and it doesn't seem to me that is huge. It is very powerful but not huge.
If you want to start playing with http and python, the simplest thing is the BaseHttpServer provided in the standard library. see http://docs.python.org/library/basehttpserver.html for details
I agree with Paolo - Django is pretty small and the way to go - but if you are not down with that I would add to TurboGears to the list
If you are looking for a framework take a look at this list: Python Web Frameworks
If you need small script(-s) or one time job script, might be plain CGI module is going to be enough - CGI Scripts and cgi module itself.
I would recommend you to stick to some framework if you want to create something more then static pages and simple forms. Django is I believe most popular and most supported.
What is "huge" is a matter of taste, but Django is a "full stack" framework, that includes everything from an ORM, to templates to well, loads of things. So it's not small (although smaller than Grok and Zope3, other full-stack python web frameworks).
But there are also plenty of really small and minimalistic web frameworks, that do nothing than provide a framework for the web part. Many have been mentioned above. To the list I must add BFG and Bobo. Both utterly minimal, but still useful and flexible.
http://bfg.repoze.org/
http://bobo.digicool.com/
I am looking for a LAMPish/WAMPish experience.
Something very transparent. Write the script, hit F5 and see the results. Very little, if any abstraction.
SQLAlchemy and (maybe) some simple templating engine will be used.
I need simple access to the environment - similar to the PHP way. Something like the COOKIE, SESSION, POST, GET objects.
I don't want to write a middleware layer just to get some web serving up and running. And I do not want to deal with specifics of CGI.
This is not meant for a very complex project and it is for beginning programmers and/or beginning Python programmers.
An MVC framework is not out of the question. ASP.NET MVC is nicely done IMO. One thing I liked is that POSTed data is automatically cast to data model objects if so desired.
Can you help me out here?
Thanks!
PS: I did not really find anything matching these criteria in older posts.
CherryPy might be what you need. It transparently maps URLs onto Python functions, and handles all the cookie and session stuff (and of course the POST / GET parameters for you).
It's not a full-stack solution like Django or Rails. On the other hand, that means that it doesn't lump you with a template engine or ORM you don't like; you're free to use whatever you like.
It includes a WSGI compliant web server, so you don't even need Apache.
For low barrier to entry, web.py is very very light and simple.
Features:
easy (dev) deploy... copy web.py folder into your app directory, then start the server
regex-based url mapping
very simple class mappings
built-in server (most frameworks have this of course)
very thin (as measured by lines of code, at least) layer over python application code.
Here is its hello world:
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()
As much as I like Werkzeug conceptually, writing wsgi plumbing in the Hello, World! is deeply unpleasant, and totally gets in the way of actually demoing an app.
That said, web.py isn't perfect, and for big jobs, it's probably not the right tool, since:
routes style systems are (imho) better than pure regex ones
integrating web.py with other middlewares might be adventurous
What you're describing most resembles Pylons, it seems to me. However, the number of web frameworks in/for Python is huge -- see this page for an attempt to list and VERY briefly characterize each and every one of them!-)
Have you looked into the Django web framework? Its an MVC framework written in python, and is relatively simple to set up and get started. You can run it with nothing but python, as it can use SQLite and its own development server, or you can set it up to use MySQL and Apache if you'd like.
Pylons is another framework that supports SQLAlchemy for models. I've never used it but it seems promising.
Look at:
WSGI, the standard Python API for HTTP servers to call Python code.
Django, a popular, feature-rich, well documented Python web framework
web.py, a minimal Python web framework
Don't forget Bottle. It is a single-file micro web framework with no dependencies and very easy to use. Here is an "Hello world" example:
from bottle import route, run
#route('/')
def index():
return 'Hello World!'
run(host='localhost', port=8080)
And here an example for accessing POST variables (cookies and GET vars are similar)
from bottle import route, request
#route('/submit', method='POST')
def submit():
name = request.POST.get('name', 'World')
return 'Hello %s!' % name
Check out web2py. It runs out of the box with no configuration - even from a USB stick. The template language is pure Python and you can develop your entire app through the browser editor (although I find vim faster ;)