Python web framework with low barrier to entry - python

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 ;)

Related

Web application with python

I have a Python program that takes one input (string) and prints out several lines as an output. I was hoping to get it online, so that the web page only has a text-area and a button. Inserting a string and pressing the button should send the string to python and make the original page print out the output from Python.
Assuming I have only dealt with Python and a little bit of HTML and have very limited knowledge about the web, how might I approach this problem?
For some reason, my first instinct was PHP, but Googling "PHP Python application" didn't really help.
That is, assuming what I want IS a 'web application', right? Not a web server, web page or something else?
How could I get a really simple version (like in the first paragraph) up and running, and where to learn more?
Yes, the term you're looking for is "web application". Specifically, you want to host a Python web application.
Exactly what this means, can vary. There are two main types of application - cgi and wsgi (or stand-alone, which is what most people talk about when they say "web app").
Almost nobody uses cgi nowadays, you're much more likely to come across a site using a web application framework, like Django or Flask.
If you're worried about easily making your page accessible to other people, a good option would be to use something like the free version of Heroku do to something simple like this. They have a guide available here:
https://devcenter.heroku.com/articles/getting-started-with-python#introduction
If you're more technically inclined and you're aware of the dangers of opening up your own machine to the world, you could make a simple Flask application that does this and just run it locally:
from flask import Flask, request
app = Flask(__name__)
#app.route('/')
def main():
return 'You could import render_template at the top, and use that here instead'
#app.route('/do_stuff', methods=['POST'])
def do_stuff():
return 'You posted' + request.form.get('your string')
app.run('127.0.0.1', port=5555, debug=True)
Pick a Python web development framework and follow the getting started tutorial. Main options are Django for a "batteries included" approach or Flask for a minimalistic bottom-up approach.

Is it possible to run a Python app on a WordPress site?

I have an idea for a web app and plan to learn Python as I go (right now I know html/css, some javascript, some php and sql). The app would be able to manipulate and analyze audio files, among other things.
Ideally, I'd like to make the app available through my wordpress site so that I can take advantage of WordPress's login management and the plugin s2member's subscription management and content restriction capabilities.
Is that possible? Would it even make sense?
If not, is there a better alternative to automate all of that (the subscription management, logins, payment processing, content restriction, etc) without having to code it myself?
I suggest you develop a REST API in Python and extend your Wordpress site to consume that API.
For the Python side, you could go with Flask and use Flask-RESTful.
For the Wordpress side, have a look at this question.
Sure, if you meet a couple of conditions:
The server your wordpress site is on also has python
And you have the ability run arbitrary python scripts on said server.
Here's a (very contrived) example of how to do it from a plugin:
call-python.php (plugin file):
<php
/*
Plugin name: Call Python
Author:..
....
*/
$pyScript = "/path/to/app.py";
exec("/usr/bin/python $pyScript", $output);
var_dump($output);
And the python script app.py:
print("Hello, World")
And that's it! That will dump Hello, world to the body. Obviously you'll need a bit more for a more complicated python app, but it will work.
Like others are saying, there may be better "more correct" ways of doing it. But if your end goal is to run a python app from WordPress it's possible.

How to create simple web site with Python? [closed]

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.

Simple and effective web framework

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.

Writing a website in Python

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/

Categories

Resources