Reading request parameters in Python - python

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

Related

Python CGI with API

I am quite new to python, I have built some applications in python with CGI and I found cgi is much easier compare to a framework as i have full control on everything.
Tried to build a web api through below module but it end up with a web page rather than an api.
Import cgi
Import cgitb
I would like to create a web api, as I am familiar with cgi i would like to create it (web api) through python cgi,I have been looking for a good documentation but i dint find any. It would be helpful if someone can give me a clue. I really appreciate your help.
CGI applications are nothing but backend of HTTP kind protocol, so I guess you could naturally build REST API on top of it: http://en.wikipedia.org/wiki/Representational_state_transfer
Also python have good build-in support for HTTP for better understanding from inside (in case u like to keep control on everything): https://docs.python.org/3/library/http.server.html#module-http.server
Anyway, when your getting better in it your best bet to switch on a framework like these: https://www.djangoproject.com/ http://www.tornadoweb.org/en/stable/

Will learning Django translates well into other applications?

Does anyone have experience using Python in different variaty of applications?
A little background - I am a 3D artist in an animation studio. I do programming in PHP and use Zend framework for my personal project. Python has always been a language I wanted to learn because it can be used within many applications our studio is using (3D MAX, MAYA to name a few) My supervisor knew about my web background and wanted me to create a web base time line manager for the company. From the requirement I'm expecting quite a simple backend ... so it might be a good opportunity to finally learn Python. The bulk of the work will be on AJAX for the interactive front end.
So if I learn Python with web application and Django in mind, will that limit my Python skill from applying it to other applications?
a little curious about Django features as well. How well does the framework cover in terms of web application compare to Zend? Our application is pretty basic in the back end and I would love to know if Django will be able to cover them.
authenticate against Windows active directory
quick database update via AJAX interaction (drag and drop time line mostly)
Other basic stuff like discussion forum and directory browsing/file manager
So if I learn Python with web application and Django in mind, will that limit my Python skill from applying it to other applications?
No
authenticate against Windows active directory
Yes. You may need to customize an Authentication Backend.
quick database update via AJAX interaction (drag and drop time line mostly)
Django has nothing to do with Ajax. Use piston to create pleasant RESTful API that Ajax can use.
Other basic stuff like discussion forum and directory browsing/file manager
There are many, many canned applications for Django that you can plug in and integrate.
I love python as a language - but it's not the answer to everything. I know this is throwing mud in a python group, but python has one serious limitation - the rigid source code format.
While going through a django tutorial - I noticed that you cannot insert python source code into a template, and that this was presented as a 'feature' for separating programmers and designers.
I later realized that it's a limitation of django - and any other environment where python source code might get accidentally mangled. This also includes HTML WYSIWIG editors and database based 'manglers' (like Drupal).
In my opinion it's a very serious limitation with no easy cure - especially with the need to use other tools to manage the complexity of HTML / CSS / JavaScript.
I found Django a really good way to learn python. There's very little that's quirky, magical or un-pythonic in the framework. A bit of setup and you're away, writing standard python code.

Good resources to start python for web development?

I'm really interested in learning Python for web development. Can anyone point me in the right direction? I've been looking at stuff on Google, but haven't really found anything that shows proper documentation and how to get started. Any recommended frameworks? Tutorials?
I've been doing PHP for 5 years now, so I just want to try something new.
Django is probably the best starting point. It's got great documentation and an easy tutorial (at http://djangoproject.com/) and a free online book too (http://www.djangobook.com/).
Web Server Gateway Interface
About
http://www.wsgi.org/en/latest/index.html
http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface
Tutorials
http://webpython.codepoint.net/wsgi_tutorial
http://lucumr.pocoo.org/2007/5/21/getting-started-with-wsgi/
http://archimedeanco.com/wsgi-tutorial/
There are three major parts to python web frameworks, in my experience. From the front to back:
Views/Templates: Application frameworks don't function as independent scripts - instead, you map paths to python functions or objects which return html. To generate the html you probably need templates (aka views). Check out Cheetah.
Application framework/Server: There are plenty. CherryPy is my favorite, and is good for understanding how a python application server works because a) it's simple and b) unlike django and others, it is just the application server and doesn't include a templating engine or a database abstraction layer.
Database layer: I've actually never used it, but everyone seems to like SQLAlchemy. I prefer, in simple applications, executing SQL directly using a tool like psycopg2 (for postgres).
You can try Django. It's easy to learn, and it works with GAE (though the default version is 0.96, a little bit old, but you can change it). And there's a video about rapid development (by Guido Van Rossum) that goes through the basics of setting up a Django project in App Engine.

Python for web scripting

I'm just starting out with Python and have practiced so far in the IDLE interface. Now I'd like to configure Python with MAMP so I can start creating really basic webapps — using Python inside HTML, or well, vice-versa. (I'm assuming HTML is allowed in Python, just like PHP? If not, are there any modules/template engines for that?)
What modules do I need to install to run .py from my localhost? Googling a bit, it seems there're various methods — mod_python, FastCGI etc.. which one should I use and how to install it with MAMP Pro 1.8.2?
Many thanks
I think probably the easiest way for you to get started is to work with something like Django. It's a top-to-bottom web development stack which provides you with everything you need to develop and run a backend server. Things can be very simple in that world, no need to mess around with mod_python or FastCGI unless you really have the need.
It's also nice because it conforms to WSGI, which is a Python standard which allows you to plug together unrelated bits of reusable code to add specific functionality to your web app when needed (say for example on-the-fly gzip compression, or OpenID authentication). Once you have outgrown the default Django stack, or want to change something specific you can go down this road if you want.
Those are a few pointers to get you started. You could also look at other alternative frameworks such as TurboGears or paste if you wanted but Django is a great way to get something up and running quickly. Anyway, I'm sure you'll enjoy the experience: WSGI makes it a real joy knocking up web apps with the wealth of Python code you'll find on the web.
[edit: you may find it helpful to browse some of the may Django related questions here on stack-overflow if you run into problems]
You asked whether HTML is allowed within Python, which indicates that you still think too much in PHP terms about it. Contrary to PHP, Python was not designed to create dynamic web-pages. Instead, it was designed as a stand-alone, general-purpose programming language. Therefore you will not be able to put HTML into Python. There are some templating libraries which allow you to go the other way around, somewhat, but that's a completely different issue.
With things like Django or TurboGears or all the other web-frameworks, you essentially set up a small, stand-alone web-server (which comes bundled with the framework so you don't have to do anything), tell the server which function should handle what URL and then write those functions. In the simplest case, each URL you specify has its own function.
That 'handler function' (or 'view function' in Django terminology) receives a request object in which interesting info about the just-received request is contained. It then does whatever processing is required (a DB query for example). Finally, it produces some output, which is returned to the client. A typical way to get the output is to have some data passed to a template where it is rendered together with some HTML.
So, the HTML is separated in a template (in the typical case) and is not in the Python code.
About Python 3: I think you will find that the vast majority of all Python development going on in the world is still with Python 2.*. As others have pointed out here, Python 3 is just coming out, most of the good stuff is not available for it yet, and you shouldn't be bothered about that.
My advise: Grab yourself Python 2.6 and Django 1.1 and dive in. It's fun.
Django is definitely not the easiest way.
check out pylons. http://pylonshq.com/
also check sqlalchemy for sql related stuff. Very cool library.
On the other hand, you can always start with something very simple like mako for templating. http://www.makotemplates.org/

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