- 浏览: 461546 次
- 性别:
- 来自: 坚持零分
文章分类
最新评论
-
wzwahl36:
文章非常赞,http://www.atool.org/img2 ...
在浏览器中解析Base64编码图像 -
realyasswl:
ie sucks
IE9 媲美Firebug的强大的程序员开发工具 -
di1984HIT:
不错啊。呵呵。
MS的一些小工具 -
NothingCanBeDone:
楼主,你这Project,能放出来了,感激不尽。
[Ray Linn]用Visual Studio 2008开发IE BHO(浏览器帮助对象) 之三 -
烬难烬:
这就没了???我去....
IE9 媲美Firebug的强大的程序员开发工具
The classical "Hello World" in python CGI fashion:
#!/usr/bin/env python
print "Content-Type: text/html"
print
print """\
<html>
<body>
<h2>Hello World!
</body>
</html>
"""
To test your setup save it with the .py extension, upload it to your server as text and make it executable before trying to run it.
The first line of a python CGI script sets the path where the python interpreter will be found in the server. Ask your provider what is the correct one. If it is wrong the script will fail. Some examples:
#!/usr/bin/python
#!/usr/bin/python2.3
#!/usr/bin/python2.4
It is necessary that the script outputs the HTTP header. The HTTP header consists of one or more messages followed by a blank line. If the output of the script is to be interpreted as HTML then the content type will be text/html. The blank line signals the end of the header and is required.
print "Content-Type: text/html"
print
If you change the content type to text/plain the browser will not interpret the script's output as HTML but as pure text and you will only see the HTML source. Try it now to never forget. A page refresh may be necessary for it to work.
Client versus Server
All python code will be executed at the server only. The client's agent (for example the browser) will never see a single line of python. Instead it will only get the script's output. This is something realy important to understand.
When programming for the Web you are in a client-server environment, that is, do not make things like trying to open a file in the client's computer as if the script were running there. It isn't.
How to Debugging in python?
Syntax and header errors are hard to catch unless you have access to the server logs. Syntax error messages can be seen if the script is run in a local shell before uploading to the server.
For a nice exceptions report there is the cgitb module. It will show a traceback inside a context. The default output is sent to standard output as HTML:
#!/usr/bin/env python
print "Content-Type: text/html"
print
import cgitb; cgitb.enable()
print 1/0
The handler() method can be used to handle only the catched exceptions:
#!/usr/bin/env python
print "Content-Type: text/html"
print
import cgitb
try:
f = open('non-existent-file.txt', 'r')
except:
cgitb.handler()
There is also the option for a crude approach making the header "text/plain" and setting the standard error to standard out:
#!/usr/bin/env python
print "Content-Type: text/plain"
print
import sys
sys.stderr = sys.stdout
f = open('non-existent-file.txt', 'r')
Will output this:
Traceback (most recent call last):
File "/var/www/html/teste/cgi-bin/text_error.py", line 6, in ?
f = open('non-existent-file.txt', 'r')
IOError: [Errno 2] No such file or directory: 'non-existent-file.txt'
Warning: These techniques expose information that can be used by an attacker. Use it only while developing/debugging. Once in production disable it.
How to use Cookies for Web python ?
HTTP is said to be a stateless protocol. What this means for web programmers is that every time a user loads a page it is the first time for the server. The server can't say whether this user has ever visited that site, if is he in the middle of a buying transaction, if he has already authenticated, etc.
A cookie is a tag that can be placed on the user's computer. Whenever the user loads a page from a site the site's script can send him a cookie. The cookie can contain anything the site needs to identify that user. Then within the next request the user does for a new page there goes back the cookie with all the pertinent information to be read by the script.
* Set the Cookie;
There are two basic cookie operations. The first is to set the cookie as an HTTP header to be sent to the client. The second is to read the cookie returned from the client also as an HTTP header.
This script will do the first one placing a cookie on the client's browser:
#!/usr/bin/env python
import time
# This is the message that contains the cookie
# and will be sent in the HTTP header to the client
print 'Set-Cookie: lastvisit=' + str(time.time());
# To save one line of code
# we replaced the print command with a '\n'
print 'Content-Type: text/html\n'
# End of HTTP header
print '<html><body>'
print 'Server time is', time.asctime(time.localtime())
print '</body></html>'
The Set-Cookie header contains the cookie. Save and run this code from your browser and take a look at the cookie saved there. Search for the cookie name, lastvisit, or for the domain name, or the server IP like 10.1.1.1 or 127.0.0.1.
The Cookie Object
The Cookie module can save us a lot of coding and errors and the next pages will use it in all cookie operations.
#!/usr/bin/env python
import time, Cookie
# Instantiate a SimpleCookie object
cookie = Cookie.SimpleCookie()
# The SimpleCookie instance is a mapping
cookie['lastvisit'] = str(time.time())
# Output the HTTP message containing the cookie
print cookie
print 'Content-Type: text/html\n'
print '<html><body>'
print 'Server time is', time.asctime(time.localtime())
print '</body></html>'
It does not seem as much for this extremely simple code, but wait until it gets complex and the Cookie module will be your friend.
* Retrieve the Cookie;
The returned cookie will be available as a string in the os.environ dictionary with the key 'HTTP_COOKIE':
cookie_string = os.environ.get('HTTP_COOKIE')
The load() method of the SimpleCookie object will parse that string rebuilding the object's mapping:
cookie.load(cookie_string)
Complete code:
#!/usr/bin/env python
import Cookie, os, time
cookie = Cookie.SimpleCookie()
cookie['lastvisit'] = str(time.time())
print cookie
print 'Content-Type: text/html\n'
print '<html><body>'
print '<p>Server time is', time.asctime(time.localtime()), '</p>'
# The returned cookie is available in the os.environ dictionary
cookie_string = os.environ.get('HTTP_COOKIE')
# The first time the page is run there will be no cookies
if not cookie_string:
print '<p>First visit or cookies disabled</p>'
else: # Run the page twice to retrieve the cookie
print '<p>The returned cookie string was "' + cookie_string + '"</p>'
# load() parses the cookie string
cookie.load(cookie_string)
# Use the value attribute of the cookie to get it
lastvisit = float(cookie['lastvisit'].value)
print '<p>Your last visit was at',
print time.asctime(time.localtime(lastvisit)), '</p>'
print '</body></html>'
When the client first loads the page there will be no cookie in the client's computer to be returned. The second time the page is requested then the cookie saved in the last run will be sent to the server.
* Morsels
In the previous cookie retrieve program the lastvisit cookie value was retrieved through its value attribute:
lastvisit = float(cookie['lastvisit'].value)
When a new key is set for a SimpleCookie object a Morsel instance is created:
>>> import Cookie
>>> import time
>>>
>>> cookie = Cookie.SimpleCookie()
>>> cookie
<SimpleCookie: >
>>>
>>> cookie['lastvisit'] = str(time.time())
>>> cookie['lastvisit']
<Morsel: lastvisit='1159535133.33'>
>>>
>>> cookie['lastvisit'].value
'1159535133.33'
Each cookie, a Morsel instance, can only have a predefined set of keys: expires, path, commnent, domain, max-age, secure and version. Any other key will raise an exception.
#!/usr/bin/env python
import Cookie, time
cookie = Cookie.SimpleCookie()
# name/value pair
cookie['lastvisit'] = str(time.time())
# expires in x seconds after the cookie is output.
# the default is to expire when the browser is closed
cookie['lastvisit']['expires'] = 30 * 24 * 60 * 60
# path in which the cookie is valid.
# if set to '/' it will valid in the whole domain.
# the default is the script's path.
cookie['lastvisit']['path'] = '/cgi-bin'
# the purpose of the cookie to be inspected by the user
cookie['lastvisit']['comment'] = 'holds the last user\'s visit date'
# domain in which the cookie is valid. always stars with a dot.
# to make it available in all subdomains
# specify only the domain like .my_site.com
cookie['lastvisit']['domain'] = '.www.my_site.com'
# discard in x seconds after the cookie is output
# not supported in most browsers
cookie['lastvisit']['max-age'] = 30 * 24 * 60 * 60
# secure has no value. If set directs the user agent to use
# only (unspecified) secure means to contact the origin
# server whenever it sends back this cookie
cookie['lastvisit']['secure'] = ''
# a decimal integer, identifies to which version of
# the state management specification the cookie conforms.
cookie['lastvisit']['version'] = 1
print 'Content-Type: text/html\n'
print '<p>', cookie, '</p>'
for morsel in cookie:
print '<p>', morsel, '=', cookie[morsel].value
print '<div style="margin:-1em auto auto 3em;">'
for key in cookie[morsel]:
print key, '=', cookie[morsel][key], '<br />'
print '</div>
#!/usr/bin/env python
print "Content-Type: text/html"
print """\
<html>
<body>
<h2>Hello World!
</body>
</html>
"""
To test your setup save it with the .py extension, upload it to your server as text and make it executable before trying to run it.
The first line of a python CGI script sets the path where the python interpreter will be found in the server. Ask your provider what is the correct one. If it is wrong the script will fail. Some examples:
#!/usr/bin/python
#!/usr/bin/python2.3
#!/usr/bin/python2.4
It is necessary that the script outputs the HTTP header. The HTTP header consists of one or more messages followed by a blank line. If the output of the script is to be interpreted as HTML then the content type will be text/html. The blank line signals the end of the header and is required.
print "Content-Type: text/html"
If you change the content type to text/plain the browser will not interpret the script's output as HTML but as pure text and you will only see the HTML source. Try it now to never forget. A page refresh may be necessary for it to work.
Client versus Server
All python code will be executed at the server only. The client's agent (for example the browser) will never see a single line of python. Instead it will only get the script's output. This is something realy important to understand.
When programming for the Web you are in a client-server environment, that is, do not make things like trying to open a file in the client's computer as if the script were running there. It isn't.
How to Debugging in python?
Syntax and header errors are hard to catch unless you have access to the server logs. Syntax error messages can be seen if the script is run in a local shell before uploading to the server.
For a nice exceptions report there is the cgitb module. It will show a traceback inside a context. The default output is sent to standard output as HTML:
#!/usr/bin/env python
print "Content-Type: text/html"
import cgitb; cgitb.enable()
print 1/0
The handler() method can be used to handle only the catched exceptions:
#!/usr/bin/env python
print "Content-Type: text/html"
import cgitb
try:
f = open('non-existent-file.txt', 'r')
except:
cgitb.handler()
There is also the option for a crude approach making the header "text/plain" and setting the standard error to standard out:
#!/usr/bin/env python
print "Content-Type: text/plain"
import sys
sys.stderr = sys.stdout
f = open('non-existent-file.txt', 'r')
Will output this:
Traceback (most recent call last):
File "/var/www/html/teste/cgi-bin/text_error.py", line 6, in ?
f = open('non-existent-file.txt', 'r')
IOError: [Errno 2] No such file or directory: 'non-existent-file.txt'
Warning: These techniques expose information that can be used by an attacker. Use it only while developing/debugging. Once in production disable it.
How to use Cookies for Web python ?
HTTP is said to be a stateless protocol. What this means for web programmers is that every time a user loads a page it is the first time for the server. The server can't say whether this user has ever visited that site, if is he in the middle of a buying transaction, if he has already authenticated, etc.
A cookie is a tag that can be placed on the user's computer. Whenever the user loads a page from a site the site's script can send him a cookie. The cookie can contain anything the site needs to identify that user. Then within the next request the user does for a new page there goes back the cookie with all the pertinent information to be read by the script.
* Set the Cookie;
There are two basic cookie operations. The first is to set the cookie as an HTTP header to be sent to the client. The second is to read the cookie returned from the client also as an HTTP header.
This script will do the first one placing a cookie on the client's browser:
#!/usr/bin/env python
import time
# This is the message that contains the cookie
# and will be sent in the HTTP header to the client
print 'Set-Cookie: lastvisit=' + str(time.time());
# To save one line of code
# we replaced the print command with a '\n'
print 'Content-Type: text/html\n'
# End of HTTP header
print '<html><body>'
print 'Server time is', time.asctime(time.localtime())
print '</body></html>'
The Set-Cookie header contains the cookie. Save and run this code from your browser and take a look at the cookie saved there. Search for the cookie name, lastvisit, or for the domain name, or the server IP like 10.1.1.1 or 127.0.0.1.
The Cookie Object
The Cookie module can save us a lot of coding and errors and the next pages will use it in all cookie operations.
#!/usr/bin/env python
import time, Cookie
# Instantiate a SimpleCookie object
cookie = Cookie.SimpleCookie()
# The SimpleCookie instance is a mapping
cookie['lastvisit'] = str(time.time())
# Output the HTTP message containing the cookie
print cookie
print 'Content-Type: text/html\n'
print '<html><body>'
print 'Server time is', time.asctime(time.localtime())
print '</body></html>'
It does not seem as much for this extremely simple code, but wait until it gets complex and the Cookie module will be your friend.
* Retrieve the Cookie;
The returned cookie will be available as a string in the os.environ dictionary with the key 'HTTP_COOKIE':
cookie_string = os.environ.get('HTTP_COOKIE')
The load() method of the SimpleCookie object will parse that string rebuilding the object's mapping:
cookie.load(cookie_string)
Complete code:
#!/usr/bin/env python
import Cookie, os, time
cookie = Cookie.SimpleCookie()
cookie['lastvisit'] = str(time.time())
print cookie
print 'Content-Type: text/html\n'
print '<html><body>'
print '<p>Server time is', time.asctime(time.localtime()), '</p>'
# The returned cookie is available in the os.environ dictionary
cookie_string = os.environ.get('HTTP_COOKIE')
# The first time the page is run there will be no cookies
if not cookie_string:
print '<p>First visit or cookies disabled</p>'
else: # Run the page twice to retrieve the cookie
print '<p>The returned cookie string was "' + cookie_string + '"</p>'
# load() parses the cookie string
cookie.load(cookie_string)
# Use the value attribute of the cookie to get it
lastvisit = float(cookie['lastvisit'].value)
print '<p>Your last visit was at',
print time.asctime(time.localtime(lastvisit)), '</p>'
print '</body></html>'
When the client first loads the page there will be no cookie in the client's computer to be returned. The second time the page is requested then the cookie saved in the last run will be sent to the server.
* Morsels
In the previous cookie retrieve program the lastvisit cookie value was retrieved through its value attribute:
lastvisit = float(cookie['lastvisit'].value)
When a new key is set for a SimpleCookie object a Morsel instance is created:
>>> import Cookie
>>> import time
>>>
>>> cookie = Cookie.SimpleCookie()
>>> cookie
<SimpleCookie: >
>>>
>>> cookie['lastvisit'] = str(time.time())
>>> cookie['lastvisit']
<Morsel: lastvisit='1159535133.33'>
>>>
>>> cookie['lastvisit'].value
'1159535133.33'
Each cookie, a Morsel instance, can only have a predefined set of keys: expires, path, commnent, domain, max-age, secure and version. Any other key will raise an exception.
#!/usr/bin/env python
import Cookie, time
cookie = Cookie.SimpleCookie()
# name/value pair
cookie['lastvisit'] = str(time.time())
# expires in x seconds after the cookie is output.
# the default is to expire when the browser is closed
cookie['lastvisit']['expires'] = 30 * 24 * 60 * 60
# path in which the cookie is valid.
# if set to '/' it will valid in the whole domain.
# the default is the script's path.
cookie['lastvisit']['path'] = '/cgi-bin'
# the purpose of the cookie to be inspected by the user
cookie['lastvisit']['comment'] = 'holds the last user\'s visit date'
# domain in which the cookie is valid. always stars with a dot.
# to make it available in all subdomains
# specify only the domain like .my_site.com
cookie['lastvisit']['domain'] = '.www.my_site.com'
# discard in x seconds after the cookie is output
# not supported in most browsers
cookie['lastvisit']['max-age'] = 30 * 24 * 60 * 60
# secure has no value. If set directs the user agent to use
# only (unspecified) secure means to contact the origin
# server whenever it sends back this cookie
cookie['lastvisit']['secure'] = ''
# a decimal integer, identifies to which version of
# the state management specification the cookie conforms.
cookie['lastvisit']['version'] = 1
print 'Content-Type: text/html\n'
print '<p>', cookie, '</p>'
for morsel in cookie:
print '<p>', morsel, '=', cookie[morsel].value
print '<div style="margin:-1em auto auto 3em;">'
for key in cookie[morsel]:
print key, '=', cookie[morsel][key], '<br />'
print '</div>
发表评论
-
Python Interview Questions And Answers Set - 5
2011-05-16 20:48 2444How do I send mail from a Pytho ... -
Python Interview Questions And Answers Set - 4
2011-05-16 20:41 2076How do I make a Python script e ... -
Ruby对多线程的支持
2011-02-28 10:46 55861. 我们通常说的Ruby,一 ... -
Ironruby 1.1发布了....
2010-07-18 13:23 1294Ironruby是兼容ruby 1.8.6的.NET实现,自从 ... -
【系统管理】利用脚本操作VHD以及VBOX虚拟机
2010-06-17 17:10 3552做系统管理时,常常需要为网内的机器制作一些Image,利用VH ... -
[IronRuby] C# 4.0调用ActiveRecord
2010-05-19 16:44 2449DLR引擎是一个通用的平台和承载模型,使动态语言可在 Micr ... -
ironruby 控制乌龟爬
2010-05-13 22:25 1274现在可以用ironruby控制乌龟爬了 up 10 lt ... -
【乌龟爬】之.NET中的嵌入语言与宿主的交互
2010-05-11 21:47 1576这个题目已经弄清楚了,可以研究一下进阶阶段的内容了,所以改了题 ... -
利用MKMF编写Ruby的Windows扩展 之二
2010-05-06 14:39 1290先占个坑吧,回头再总结一些林林总总的东西 C:\dosbin ... -
【工作点滴】用VS 2010 编译 Ruby 1.9.1
2010-04-22 20:43 4066关键字:ruby 1.9.1 Visual studio 20 ... -
【Ray谈Ruby] 利用MKMF编写Ruby的Windows扩展 之一
2010-03-31 16:54 3396MKMF可以帮你自动成Ruby扩展库的Makefile,这样生 ... -
扩展Ironruby
2010-03-28 20:54 1396在公司里,选择ruby作为 ... -
【IronRuby】细谈Ironruby与.NET的互操作性
2009-12-02 11:30 1716作者: Ray Linn 最后更 ... -
[IronRuby] IronRuby 1.0及与.NET互操作
2009-11-24 12:09 1611ironruby 是.Net平台下的一个ruby实现,众所周知 ... -
IronRuby: Rails-Like MVC without Rails
2008-11-13 10:51 2363IronRuby是.NET下的一个Ruby ...
相关推荐
SAP Basis Interview Questions 在进行 SAP Basis 的面试准备时,面试官通常会关注应聘者对 SAP Basis 的基础知识和实践经验的理解。例如: - **问题示例**:“请简要介绍 SAP Basis 并解释它的主要功能。” - **...
从国外网站上下载的Java面试题。可以看看国外公司的Java面试常用题,以及如何用英文回答。
115-Java-Interview-Questions-and-Answers, 115 Java访谈问题和答案- 终极列表 #115-Java-Interview-Questions-and-Answers我们将讨论关于Java面试中可以使用的各种问题,以便雇主在Java和面向对象编程方面测试你的...
根据提供的文件信息,本文将对其中涉及的C++面试题目进行详细解析,并提供相应的答案,旨在帮助准备参加C++职位面试的求职者更好地理解和掌握相关的技术要点。 ### 1. C++基础知识 #### 1.1 什么是C++?...
### Java Interview Questions and Answers #### 1. 什么是 Java?解释其含义与定义。 Java 是当今最流行的编程语言之一,在 Web 应用程序、移动应用、软件开发、游戏系统以及服务器端技术等领域扮演着重要角色。...
CISA Interview Questions and Answers学习文档手册.pdf
根据提供的文件信息,我们可以从中提炼出三个重要的面试问题及其回答策略。这不仅是对求职者面试技巧的考验,也是展示个人专业素养与职业态度的关键时刻。接下来,我们将详细解析这三个问题及如何给出恰当的回答。...
### IT面试问题与答案解析 #### 1. 如何描述自己? **优秀示例回答:** 我的背景至今一直围绕着成为一名最优秀的财务顾问而努力。让我具体介绍一下我是如何准备自己的。我是一名在______大学主修金融和会计的本科...
SAP ABAP Certification Review SAP ABAP Interview Questions, Answers, And Explanations.pdf
SAP SD(Sales and Distribution)是SAP ERP中的一个核心模块,主要用于管理企业的销售流程和物流配送过程。对于希望进入SAP领域的专业人士来说,掌握SD模块的相关知识非常重要。本文将基于SAP SD面试常见问题及其...
本资料“Java-Spring-Boot-Interview-Questions-and-Answers”集合了最受欢迎的Java及Spring Boot面试问题,帮助求职者准备相关面试。 一、Java基础 1. 讲解Java内存模型(JVM)的结构,包括堆内存、栈内存、方法区...
- **设置可编辑模式**: 使用 `set_read_only` 方法将 ALV 设置为可编辑模式,该方法在接口 `IF_SALV_WD_TABLE_SETTINGS` 实现类 `CL_SALV_WD_CONFIG_TABLE` 中定义。 #### 9. 如何在 WebDynpro 中导航视图 **知识...
7. 如何控制块级元素与行内元素,以及如何合理使用它们。 8. 浮动元素的使用方法、可能出现的问题及其解决策略。 9. HTML与XHTML的区别,并根据自己的理解决定应该使用哪一个。 10. JSON的作用和用途,以及设计良好...
根据提供的文件信息,我们可以深入探讨SAP CRM领域的一系列关键面试问题及答案,这些问题涵盖了从组织模型、业务伙伴创建到系统集成等多个方面。下面将详细解释这些知识点。 ### 组织模型 **问题:** ...
pku acm 2371 Questions and answers代码 采用二叉查找树排序,解题报告请访问:http://blog.csdn.net/china8848
Vi and Vim: Questions and Answers takes some of the best questions and answers asked on the vi.stackexchange.com website. You can use this book to look up commonly asked questions, browse questions ...
《CISM Review Questions, Answers -amp- Explanations Manual 9th》是ISACA认证CISM(Certified Information Security Manager)考试的重要参考资料,它包含了针对CISM考试的全面复习问题、答案以及详尽的解释。...
7. Vue.js 指令 Vue.js 指令是一种特殊的 HTML 元素,用于告诉 Vue.js 库如何处理某个 DOM 元素。常用的 Vue.js 指令包括 v-bind、v-model、v-on 等。 8. Vue.js 组件 Vue.js 组件是 Vue.js 应用程序的基本构成...
This book covers useful Interview Questions and Answers on ASP.NET MVC. This book is appropriate for novice as well as for senior level professionals who wants to strengthen their skills before ...