[Medusa-dev] psp_handler - embed python in HTML like ASP

[Medusa-dev] psp_handler - embed python in HTML like ASP

Kevin Smith smithk at attbi.com
Sun Apr 27 13:27:49 EDT 2003

 


Hi, I have created a psp_handler (Python Server Pages???) for medusa
based on the script_handler. This handler lets you mix HTML with python
like ASP pages. The handler can be installed on the server in the sam
manner as the script handler.
Here is an example hello.psp file... <html>
<title>Medusa PSP Handler</title>
<body>
<%psp
print "hello world"
%>
</body>
</html> I have been using this handler for much more useful applications of
course :). Just wrap the inline python with <%psp ... %> tags. Here is the handler...
# -*- Mode: Python -*- # This is a simple python server pages script handler. # A note about performance: This is really only suited for 'fast'
# scripts: The script should generate its output quickly, since the
# whole web server will stall otherwise. This doesn't mean you have
# to write 'fast code' or anything, it simply means that you shouldn't
# call any long-running code, [like say something that opens up an
# internet connection, or a database query that will hold up the
# server]. If you need this sort of feature, you can support it using
# the asynchronous I/O 'api' that the rest of medusa is built on. [or
# you could probably use threads] # Put your script into your web docs directory (like a cgi-bin
# script), make sure it has the correct extension [see the overridable
# script_handler.extension member below].
#
# There's lots of things that can be done to tweak the restricted
# execution model. Also, of course you could just use 'execfile'
# instead (this is now the default, see class variable
# script_handler.restricted) import rexec
import re
import string
import StringIO
import sys import counter
import default_handler
import producers
from script_handler import collector unquote = default_handler.unquote def iif(expression,truepart,falsepart):
if expression:
return truepart
else:
return falsepart class psp_handler: extension = 'psp' # the following should not get overridden!
fp = None
script = ''
data = ''
insidePsp = False script_regex = re.compile (
r'.*/([^/]+\.%s)' % extension,
re.IGNORECASE
) def __init__ (self,
filesystem,restricted=False,preserveNamespace=True):
self.filesystem = filesystem
self.hits = counter.counter()
self.exceptions = counter.counter()
self.restricted = restricted
self.preserveNamespace = preserveNamespace def match (self, request):
[path, params, query, fragment] = request.split_uri()
m = self.script_regex.match (path)
return (m and (m.end() == len(path))) def handle_request (self, request): [path, params, query, fragment] = request.split_uri() while path and path[0] == '/':
path = path[1:] if '%' in path:
path = unquote (path) if not self.filesystem.isfile (path):
request.error (404)
return
else: self.hits.increment() request.script_filename = self.filesystem.translate (path) if request.command in ('PUT', 'POST'):
# look for a Content-Length header.
cl = request.get_header ('content-length')
length = int(cl)
if not cl:
request.error (411)
else:
collector (self, length, request)
else:
self.continue_request (
request,
StringIO.StringIO() # empty stdin
) def continue_request (self, request, stdin):
temp_files = stdin, StringIO.StringIO(), StringIO.StringIO()
old_files = sys.stdin, sys.stdout, sys.stderr try:
sys.request = request
sys.stdin, sys.stdout, sys.stderr = temp_files
try:
#get the path from the uri and open the file with the
filesystem class
try:
file =
self.filesystem.open(request.split_uri()[0],'r')
except IOError:
request.error (404)
return
self.fp = producers.file_producer(file)
self.dissect_psp(request)
request.reply_code = 200
except:
request.reply_code = 500
self.exceptions.increment()
finally:
sys.stdin, sys.stdout, sys.stderr = old_files
del sys.request i,o,e = temp_files if request.reply_code != 200:
s = e.getvalue()
else:
s = o.getvalue() request['Content-Length'] = len(s)
request.push (s)
request.done() def status (self):
return producers.simple_producer (
'<li>PSP - Python Server Pages Handler'
+ '<ul>'
+ ' <li><b>Hits:</b> %s' % self.hits
+ ' <li><b>Exceptions:</b> %s' % self.exceptions
+ ' <li><b>Execution Mode:</b>%s' %
iif(self.restricted,'Restricted','Unrestricted' )
+ ' <li><b>Namespace:</b>:%sPreserved' %
iif(self.preserveNamespace,'','not ' )
+ '</ul>'
) ## this function reads the file using the file producer and sends
## the data to the client until the script start tag '<%psp'
## is found. All of the text between the script start marker
## '<%psp' and the end script marker '%>' is executed as
## python script.
def dissect_psp(self,request):
self.insidePsp = False
self.script = ''
while not self.fp.done:
self.data=self.fp.more()
#print the HTML to the stdout, execute the python script...
while self.data:
if self.insidePsp:
sectionend=self.data.find("%>")
if (sectionend == -1):
#end of script section is not in the current
chunk
self.script += self.data
self.data = ''
else:
#end of script section is within the current
chunk
self.script += self.data[:sectionend]
self.data = self.data[sectionend+len("%>"):]
del sectionend
if self.preserveNamespace:
if self.restricted:
r = rexec.RExec()
try:
if self.restricted:
r.s_exec (self.script)
else:
exec (self.script)
request.reply_code = 200
except:
request.reply_code = 500
self.exceptions.increment()
else:
self.script_exec(request,self.script)
self.script = ''
self.insidePsp = False
else:
sectionend=self.data.find("<%psp")
if (sectionend == -1):
#end of HTML section is not in the current chunk
print self.data
self.data = ''
else:
#end of HTML section is within the current chunk
print self.data[:sectionend]
self.data = self.data[sectionend+len("<%psp"):]
self.insidePsp = True # this function will eliminate any of the unnecessary objects
# from appearing in the script namespace. print dir() should
# return only self,request, and script. # one drawback with this method is that namespace is cleared
# for each section of script in the document. def script_exec(self,request,script):
# for debugging we can send a copy of the script to the browser.
# this presents security issues so this next line should be
# commented out.
if self.restricted:
r = rexec.RExec()
try:
if self.restricted:
r.s_exec (script)
else:
exec (script)
request.reply_code = 200
except:
request.reply_code = 500
self.exceptions.increment()



 


[Medusa-dev] psp_handler - embed python in HTML like ASP的更多相关文章

  1. a simple and universal interface between web servers and web applications or frameworks: the Python Web Server Gateway Interface (WSGI).

    WSGI is the Web Server Gateway Interface. It is a specification that describes how a web server comm ...

  2. 跟着老男孩教育学Python开发【第一篇】:初识Python

    Python简介 Python前世今生 Python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解 ...

  3. Python开发【第一篇】:初识Python

    初识python 一.python简介 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解 ...

  4. python入门简介

    Python前世今生 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC ...

  5. Python开发【第二篇】:初识Python

    Python开发[第二篇]:初识Python   Python简介 Python前世今生 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏 ...

  6. python之路一

    Python前世今生 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC ...

  7. 初识Python(一)

    Python简介 Python前世今生 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解 ...

  8. Embeding Python & Extending Python with FFPython

    Introduction ffpython is a C++ lib, which is to simplify tasks that embed Python and extend Python. ...

  9. [转载]Python模块学习 ---- subprocess 创建子进程

    [转自]http://blog.sciencenet.cn/blog-600900-499638.html 最近,我们老大要我写一个守护者程序,对服务器进程进行守护.如果服务器不幸挂掉了,守护者能即时 ...

随机推荐

  1. python高级编程之元类(第3部分结束)

    # -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' #元编程 #new-style类带来了一种能力,通过2个特殊方法(_ ...

  2. Cookie知识点小结

    问题是什么?有哪些技术?如何解决? 1. Cookie 1)完成回话跟踪的一种机制:采用的是在客户端保存Http状态信息的方案 2)Cookie是在浏览器访问WEB服务器的某个资源时,由WEB服务器在 ...

  3. Scala-Partial Functions(偏函数)

    如果你想定义一个函数,而让它只接受和处理其参数定义域范围内的子集,对于这个参数范围外的参数则抛出异常,这样的函数就是偏函数(顾名思异就是这个函数只处理传入来的部分参数). 偏函数是个特质其的类型为Pa ...

  4. ArcGIS Runtime SDK for Android开发之调用GP服务(异步调用)

    一.背景说明 通过调用GP服务,Android客户端也能实现专业的.复杂的GIS分析处理功能,从而增加应用的实用价值. ArcGIS Server发布的GP服务,分为同步和异步两种类型,一般执行步骤较 ...

  5. VirtualBox 扩展包卸载或安装失败(VERR_ALREADY_EXISTS)

    最近在卸载VirtualBox出现了无法卸载的错误.提示为Failed to install the extension. The installer failed with exit code 1: ...

  6. 微信小程序demo豆瓣图书

    最近微信小程序被炒得很火热,本人也抱着试一试的态度下载了微信web开发者工具,开发工具比较简洁,功能相对比较少,个性化设置也没有.了解完开发工具之后,顺便看了一下小程序的官方开发文档,大概了解了小程序 ...

  7. 检测 HTML5\CSS3\JAVASCRIPT 在浏览器的适应情况

    CSS3 Selectors Test : 这是CSS3.INFO网站提供的css选择器测试页面,它能够详细显示当前浏览器对所有CSS3选择器的支持情况.启动测试,浏览器会自动测验,并已列表的方式显示 ...

  8. SQL SERVER 自定义函数 split

    Create function [dbo].[split] ( ), ) ) )) as begin declare @i int set @SourceSql=rtrim(ltrim(@Source ...

  9. Android adb不是内部或外部命令 (转)

    dos窗口运行adb命令出现错误:adb不是内部或外部命令…. 出现问题原因及解决办法: 1.没有配置相关环境变量. 只要将android 的sdk安装路径添加到系统变量Path中即可. (以win7 ...

  10. iOS_ @property参数分析

    @propert的相关参数 因为现在Xcode都是默认使用ARC所以现在分析主要是以ARC为主. 1.@property有哪些参数? 第一组: 内存管理特性 retain  assign  copy ...