Python3.6 My personal 101 notes
Miscellaneous operating system interfaces
import os
Common Gateway Interface support
import cgi
CGI Env Variables
http://www.cgi101.com/book/ch3/text.html
# Set content type for web browser use
print ("Content-type: text/html\n")
# Begin the web page html tags
print ("<html>")
print ("<body>")
# End the web page html tags
print ("</body>")
print ("</html>" )
# Get Values from a form
# So say form.html submites to /cgi-bin/form.py
form = cgi.FieldStorage()
if "name" not in form or "addr" not in form:
print "<H1>Error</H1>"
print "Please fill in the name and addr fields."
return
print "<p>fname:", form["fname"].value
print "<p>lname:", form["lname"].value
...further form processing here...
# Get data from fields assign to vars and print them
# using form = cgi.FieldStorage()
first_name = form.getvalue('fname')
last_name = form.getvalue('lname')
my_age = form.getvalue('age')
print (first_name)
print ("<br>")
print (last_name)
print ("<br>")
print (my_age)
print ("<br>")
# Print form values using form = cgi.FieldStorage()
print ("first name: " + form["fname"].value)
print ("<br>")
print ("last name: " + form["lname"].value)
print ("<br>")
print ("age: " + form["age"].value)
print ("<br>")
# Print some os enviroment vars
# using import os
ra = os.environ['REMOTE_ADDR']
print (ra)
print ("<br>")
ss = os.environ['SERVER_SOFTWARE']
print (ss)
print ("<br>")
# This is a formatted web ui output of some stuff
print ("Content-type: text/html\n")
print ("<html>")
print ("<body>")
print ("<h1>Hello " + first_name + " " + last_name + ". Your age is " + age + "</h1>")
print ("The IP address of your client is: " + ra)
print ("<br>")
print ("The software on this Python Server is: " + ss)
print ("</body>")
print ("</html>" )
# Read Write files with Python
http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
print ("<h1>Writing text file now to testfile.txt</h1>")
# Set file path and name as var of path
path = '/var/www/cgi-bin/testfile.txt'
file = open(path,'w')
file.write("Hello World\n")
file.write("This is our new text file\n")
file.write("and this is another line.\n")
file.write("Why? Because we can.\n")
file.close()
print ("<h1>Reading text file testfile.txt</h1>")
file = open(path,'r')
print (file.read())
file.close()
print ("<h1>Reading first 10 characters</h1>")
file = open(path,'r')
print (file.read(10))
file.close()
print ("<h1>Reading file by line</h1>")
file = open(path,'r')
print (file.readline())
file.close()
print ("<h1>Reading file all lines</h1>")
file = open(path,'r')
print (file.readlines())
file.close()
print ("<h1>Reading file looping over file object</h1>")
file = open(path,'r')
for line in file:
print (line)
...
file.close()
No comments:
Post a Comment