|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Stop making mediocre tutorials.The best tutorials are video! Camtasia Studio makes it easy to create engaging, buzz-building screen videos at any size, in any popular format. Download the free trial!
|
|
#1
|
|||
|
|||
|
CGI form
Hey, first post. Picked up Python a couple days ago as the first Laguage I am setting out to learn. I picked up a book, "Core Python Programming." It's not exactly what I wanted, but Python books are hard to find.
1. Any resources u have on Python for Web apps? 2. I am doing a Web form with 8 Text fields and 1 List field. I am using POST with default METHOD. The data is to be Verified, Stored, and Emailed. I want to error check, and show error if the 8 text fields are blank and if the 1 list is the Init value 'Select One'. Any suggestions or small samples would be greatly appreciated. I love Python so far, it is a lot more readable than anything Iv'e seen.(C++, Java, Perl) Thanks, Brett |
|
#2
|
|||
|
|||
|
For number one: You'll get some use out of this link:
http://www.python.org/cgi-bin/moinmoin/WebProgramming |
|
#3
|
||||
|
||||
|
Python Web Programming
Possibly the best book on the subject. Steve Holden's "Python Web Programming" is a definate must have for anyone interested in using Python on the web! The book teaches you everything you need to know and more in a very easy to read book and with its extensive Index, also a very handy referance.
Note: this may not be the most noobie friendly text but it is a very good read. Up to you ![]() http://www.amazon.co.uk/exec/obidos...9713953-5366211 <- amazon.co.uk http://pydish.holdenweb.com/pwp/ <- examples from the book Hope this helps, Mark. |
|
#4
|
|||
|
|||
|
Thanks, I thought that book would be good...ordering. I am sure I will be posting for help on iterating the data soon...like NOW!
I figure this might work to look for a error in form: def process(): error = ' ' form = cgi.FieldStorage() # I am not sure how I should iterate for blanks or Slect # One on List box. if not error: doResults(values) Any suggestions? |
|
#5
|
||||
|
||||
|
FieldStorage is a dictionary like object so if you treat is as such you cant go far wrong.
Code:
#!/usr/bin/ev python
import cgi
if __name__ == '__main__':
form = cgi.FieldStorage()
if 'submit' in form:
#checks if a field exists in the form. Blank form fields wont exist in
#form.
for field in form:
#do whatever with each from value
Basically this checks for the submit field in out form. then iterates over the fields in form just like a dictionary. If you want to access values in the form remember to put '.value' after the key name i.e. form['field'].value Good luck with Python , and have fun!Mark. |
|
#6
|
|||
|
|||
|
Quote:
I'm not that impressed by that book. To much low-level stuff and few details and practical examples for my taste. But it is the only book on web programming with Python. Just note that it is called "Python web programming" and not "Python web application programming". For an introduction to database programming with Python, you might as well just read the python/mysql article here on Devshed. |
|
#7
|
|||
|
|||
|
OK. I got "I think" what will work for checking the form, now I want to send an email. My web server (Imagelinkusa.net) has a Send Mail Script I can POST to.
How would or can I post the form results to that script or should I just create my own with Python. (hopefully they will install Python for me) code: Code:
#!/usr/bin/env python
import cgi
from urllib import quote_plus
from string import capwords
header = 'Content-Type: text/html\n\n'
url = '/cgi-bin/demreq.py'
errhtml = '''<HTML><HEAD><TITLE>
StoreMonitor Request Form</TITLE></HEAD>
<BODY><H3>ERROR</H3>
<B>%s</B><P>
<FORM><INPUT TYPE=button VALUE=Close
ONCLICK="window.close()"></FORM>
</BODY></HTML>'''
def showError(error_str):
print header + errhtml % (error_str)
def process():
error = ''
form = cgi.FieldStorage()
if 'submit' in form:
name = form["name"].value
comp = form["comp"].value
address = form["address"].value
city = form["city"].value
state = form["state"].value
zip = form["zip"].value
phone = form["phone"].value
register = form["register"].value
email = form["email"].value
for field in form:
# want this to email results
if not error:
error = Form is incomplete! Please click on the close button to Retry.
showError(error)
if __name__ == '__main__':
process()
What you Think? Also, who do you recommend for Hosting that have Python pre-installed? |
|
#8
|
||||
|
||||
|
Do you not get the error message appearing each time? I can't really see how that bit works. Anyway i wrote this a little while ago for sending email from Python...
Code:
def mail(address, subject, message, host = 'mail.wherever.com'):
#Create mime header from args above in the form of From, To, Subject
#and Message. Note that '\n' may be changed to '\r\n'.
message = 'From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s' % (address[0], ','.join(address[1:]), subject, message)
#SMTP functions from 'smptlib' which handle the sending of the email
#sending the email the mail server in 'host' above.
server = smtplib.SMTP(host)
server.sendmail(address[0], address[1:], message)
server.quit()
#mail(('from@somewhere.com', 'to@somewhere.com'), 'Subject', 'Message')
All you need to do is loop over the provided form values and put them into a string (or list, just as long as you pass a string to) then pass that to the mail() function. You really need to check if the form field exists (like we do with 'submit') before assigning them to variables. Since if the field doesn't exist you'll get an error. Mark. |
|
#9
|
|||
|
|||
|
Originally Posted:
Quote:
OK [if 'submit' in form:] Please give one example of WHAT to put under this to check the field. The "Python Web Programming" book gives NO help in this area. Besides the Psychology of Web Programming, I don't know why he wrote this book. It tells me about Cheetah and Webware of which crap I DON'T want to use. I want to code in Python backend through CGI and build my pages in HTML. I think an HTML book would have given more info on this than this book did. I hope I am not alienating myself here, but it is very fustrating. ![]() |
|
#10
|
|||
|
|||
|
O.K. Sorry, I looked back at chapter 11 and may have found the answer. Will this work?
Code:
def process():
form = cgi.FieldStorage()
try:
if form.has_key("name"):
name = form["name"].value
if not error:
showError('A name must be provided!')
if form.has_key("comp"):
comp = form["comp"].value
if not error:
showError('A Company must be provided!')
except:
#Fata error I guess
|
|
#11
|
||||
|
||||
|
Checking if a form field exists; or a key is in a dictionary is amazingly easy. You can do it in exactly the same way you checked if 'submit' existed i.e.
Code:
...
if submit in form:
if 'name' in form:
name = form['name'].value
...
Note: this is really just a new way to do what you're doing with has_key(). I am sorry to hear you didnt like the book. i Found it very informative and the intro to Python (at the beginning) has to be one of the nicest i've read; i learned quite alot from reading the first few chapters. Now i'm just use it as a referance book. Mark. |
|
#12
|
|||
|
|||
|
Thanks Netytan.
Now when I place in the email code and try to pass the args at the end of all the if's, it gives me an "TOKEN ERROR: EOF in multi-line statement. I know I have something wrong just not sure yet. Code:
#!/usr/lib/env python
import cgi
import smtplib
from urllib import quote_plus
header = 'Content-Type: text/html\n\n'
url = '/cgi-bin/demreq.py'
errhtml = '''<HTML><HEAD><TITLE>
StoreMonitor Demo Request Form</TITLE></HEAD>
<BODY><H3>ERROR</H3>
<B>%s</B><P>
<FORM><INPUT TYPE=button VALUE=Close
ONCLICK="window.close()"></FORM>
</BODY></HTML>'''
def showError(error_str):
print header + errhtml % (error_str)
def mail(address, subject, message, host = 'mail.haystar.com'):
message = 'From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s' % (address[0], ','.join(address[1:], subject, message)
server = smtplib.SMTP(haystar.com)
server.sendmail(address[0], address[1:], message)
server.quit()
def process():
form = cgi.FieldStorage()
try:
if form.has_key("name"):
name = form["name"].value
if not error:
showError('A name must be provided!')
if form.has_key("comp"):
comp = form["comp"].value
if not error:
showError('A Company must be provided!')
if form.has_key("address"):
address = form["address"].value
if not error:
showError('An Address must be provided!')
if form.has_key("city"):
city = form["city"].value
if not error:
showError('A City must be provided!')
if form.has_key("state"):
state = form["state"].value
if not error:
showError('A state must be provided!')
if form.has_key("zip"):
zip = form["zip"].value
if not error:
showError('A Zipcode must be provided!')
if form.has_key("phone"):
phone = form["phone"].value
if not error:
showError('A phone # must be provided!')
if form["register"].value != 'Select One':
register = form["register"].value
if not error:
showError('A register type must be provided!')
if form.has_key("email"):
email = form["email"].value
message = name\n + address\n + city\n + state\n + zip\n + phone\n + register\n + email
address[0] = 'demo@haystar.com'
address[1:] = email
mail(address[0], address[1:], message)
if not error:
showError('An email address must be provided!')
except error:
showError("Fatal Error, Form may be incomplete.")
if __name__ == '__main__':
process()
Sorry for the formatting, I can't seem to type out further than the boundaries of the box. |
|
#13
|
||||
|
||||
|
Sorry, maybe i should have mentioned this before. My mail function takes a sequance of adresses as the first argument as shown in the commented line above...
Quote:
so your line... Quote:
should look more like this... Code:
mail(address, 'Subject', message) since address is a list. I don't see anything that should cause an error. Whats the full error message saying? You do have two possible indentation problems in there: 1. your last line looks like you need to unindent it a bit. 2. sounds like the "if not error" line should be unindented a bit to but i could be wrong ![]() Mark. |
|
#14
|