[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[转载教程] snakelets文档翻译(Python 2.3或以上)

在对着zope一顿抓耳挠腮之后偶然发现了snakelets这个web server,看了看他自带的文档,一下子就喜欢上了,用我“跳楼级”的英语水平粗略的翻译了一部分想与大家分享。希望大家能够帮忙修正里面翻译的不恰当的地方(有很多哦,自己都看不过去的),从而使更多人能够了解并使用snakelets。

Starting the server, configuring

Requirements

You'll need at least Python 2.3 to run Snakelets.
你需要安装python2.3或更高版本来运行Snakelets

Please consider installing the sendfile(2) system call extension module from Snakefarm.org (works on Linux) or the one from Ben Woolley (which works on Linux and BSD too). This module may improve performance and CPU utilization in some cases (experiment!). Snakelets will automatically use it if it is installed (doesn't matter which one of the two mentioned above).
请确认安装sendfile(2) system call 扩展模块,可以到Snakefarm.org(linux操作系统)或者Ben Woolley(可以在linux和BSD上运行)下载。在某些情况下这个模块可以改善处理效率和CPU利用率(试验中!)。snakelets将会自动运行已经安装的扩展模块(无论上面提到的哪一种)。

Out-of-the-box startup

It is possible to start the Snakelets server out-of-the-box, without changing anything. If you don't enable the virtual host feature (see below), Snakelets will scan the "webapps" directory and will load all web applications it finds on the current host. If you have a web app named "ROOT" that one will be used as the web application for the root context '/'. You can just start the serv.py script without configuring anything and away you go. The default port number is 9080, so you can access the server with the following url: http://machinename.domain:9080/ .
你不用修改任何东西就可以启动snakelets server out-of-the-box(???不明白)。如果你未被授予建立虚拟主机的特权(见下文),snakelets将搜索“webapps”目录并载入所有的 web applications 到他搜索到的主机中。如果你有一个名字为“ROOT”的webapp,他将被默认为你的根目录‘/’。你可以直接运行 serv.py来启动snakelets而不需要任何修改。默认端口是9080,你可以通过 http://machinename.domain:9080访问server。

Warning: the default config works but is very likely not the one that you want for your own server environment. One of the things you will have to change is removing the example plugins (if any) and webapps that come with Snakelets!
警告:默认配置是可以正常工作的,但是您如果使用他做server环境是很不安全的。需要移除 example plugin 和 Snakelets自带的webapp。
1

评分人数

    • cjiabing: 精神可嘉,难能可贵。虽然不懂这些工具和英 ...PB + 12

看不懂英语?这不是有翻译嘛

TOP

WebApp

Snakelets run inside a WebApp context (snakeserver.webapp.WebApp). You can get the current WebApp object by calling getWebApp() on the request or the snakelet object itself. You can then use the following methods from the webapp:
Snakelet在WebApp 环境中运行(snakeserver.webapp.WebApp)。您可以在请求或snakelet对象中通过调用getWebApp()得到当前的WebApp对象。


Method                  Description


      getName()
      a tuple: (short name, full name). The short name is taken from the webapp directory it is in. Full name is specified in the webapp descriptor __init__.py file.a tuple: (short name ,full name)(好像是参数吧?)Name从webapp的目录中得到。全名被指定在webapp的描述文件 __init__.py中。

      getVirtualHost()
      a tuple (hostname, portnumber) of the 'virtual host' this webapp is running on. Does not take vhost aliasing in account; if you need the 'real' vhost and port that the request arrived on, use request.getServerName().正在运行该webapp的’虚拟主机’ 的tuple (hostname, portnumber)。请不要与vhost混淆;当请求到达是如果您需要真实vhost和端口,请使用 request.getServerName()。

      isEnabled()
      is the webapp enabled? (True or False)webapp是否允许?(True / False)。

      setEnabled(enabled)
      enable or disable this webapp开启或关闭webapp

      getFileSystemPath()
      the filesystem path where the webapp's files are located得到当前的webapp文件的文件系统路径

      getDocRootPath()
      the web document root, where the pages, images, etc are locatedweb 文档根,放置页面,图片的地方。

      getContext()
      webapp context (ContextContainer object). Scope: web app. shared for all users/requestswebapp context(ContextContainer 对象)。范围:web app。对所有用户和请求共享

      getURLprefix()
      the URL prefix that is used for urls inside this webapp (example: "/shop/" This prefix includes the (optional) server-wide prefix.得到 用于webapp url中的URL前缀(比如:”/shop/”),包括(可选择)server-wide前缀。

      getAssetprefix()
      the asset base location as specified in the WebApp's config file.得到在WebApp的配置文件中所制定的资源路径前缀。

      mkUrl(path)mkUrl(path, arg="", params=[], htmlescape=True)
      create a correct URL based on the webapp's url prefix, and automatically html-escapes the resulting string so you can directly use it in your html output. arg (optional) can be given a string that should become the url 'arg'. params (optional) can be given a dict or a sequence that contains the name/values that should become the query params. By setting the optional htmlescape param to False, no escaping will be done (and the resulting string can no longer be directly used in html output because there is a risk of generating invalid html) 建立正确的基于webapp url的前缀,并且对结果字符串自动进行html-escapes ,因此您可以在html输出中直接使用。arg(可选)参数,可以传递字符串作为url ‘arg’。 params (可选)参数,可以传递包括 name/values的dict或序列。设置 htmlescape参数为False,将不会进行html的escape操作(结果将不能直接用于html输出,因为这里在产生错误页面是存在安全问题)。


      mkAssetUrl(path)
      mkAssetUrl(path, htmlescape=True)
      create a correct URL for the static asset (images, files etc) based on the asset base location. It automatically html-escapes the resulting string so you can directly use it in your html output. By setting the optional htmlescape param to False, no escaping will be done (and the resulting string can no longer be directly used in html output because there is a risk of generating invalid html) 为静态资源创建正确的URL(images, files 等等)基于本地资源。自动对结果字符串进行html-escape,您可以在html的输出中直接使用它。通过修改 htmlescape参数选项可以关闭此功能。

      getSnakelet(urlpattern)
      returns the snakelet instance belonging to the given urlpattern (from the webapp init file)从webapp的init文件中返回属于给出的urlpattern(url样式)的snakelet实例。

      getConfigItems()
      the dictionary of all user config items所有用户配置选想的目录。

      getConfigItem(item)
      the value of a single user config item单个用户配置项的值。

      addPlugin(plugin)
      add a webapp-specific plugin (for instance to do things at session creation time). plugin is your plugin instance. If a plugin with the same name already exists, a ValueError will be raised. If your webapp is deployed on multiple vhosts, you should be prepared for this (the webapp's init code will be called multiple times). For more info, see the section on plugins.添加一个特殊插件。如果此插件名称已经存在,将产生一个ValueError的错误,如果您的webapp搭建在复合vhost上,您应该提前做好准备(wbapp的初始化代码段会被重复调用)。更多信息,请见章节 plugins


      serveStaticFile(filename, response, useResponseHeaders=False)
      Use the server's internal code to serve a static file to the client. This is useful in snakelets that return files (such as download controllers). You can fool around with setting the correct headers, and reading/writing the file efficiently to the response stream yourself, but it's usually much better to use this function instead. The response object must not be used prior to this call. You cannot set custom HTTP headers, but the required ones will be generated for you automatically (such as content-lenth). The filename must be the absolute path to to file that must be served. This must be the last action in your snakelet that generates output (the response's output must not be used at all) The file serve loop is quite efficient, and will use the sendfile system call if available. NOTE: the server's RequestPlugins are not invoked on static files! (partly due to the efficient stripped down processing code for static files to obtain higher performance) The useResponseHeaders parameter tells the server if it should add the HTTP headers from the request object (such as Cache-Control, Content-Disposition and other headers). Defaults to False. 使用内部代码为客户端提供静态文件服务。对于返回文件来说这是非常实用的(比如下载控制)。你可以通过设置正确的header 和 有效率地 读/写 文件 来反馈数据流,但是通常最好的做法是用这个函数来代替它。Response 对象一定不能在调用这个函数之前使用。您不能设置自定义的HTTP header,被请求的响应会自动帮您生成相应的header(比如 content-lenth)。提供文件服务的文件名必须是绝对路径。这必须是在snakelet中最后执行的动作,它提供的文件输出(反馈输出一定不能使用)服务循环是很高效的、如果可能还将运用到文件传送系统。主意:RequestPlugin 不能在静态文件中被导入!(部分由于分开的处理代码分别对静态文件进行处理,所以效率很高??)useResponseHeader参数告诉server 是否添加HTTP header(比如 Cache-Control, Content-Disposition 或者其他)。默认是False.

原文:http://bbs.chinaunix.net/thread-563498-1-1.html

TOP

ContextContainer

The 'context' that keeps on popping up (Request context, Snakelet context, Session context, Application context) is just a simple holder for any value you like. It is an 'empty' object that you can add your own attributes to, for instance:
所有出现的过的 ‘context’(Request context, Snakelet context, Session context, Applictaion constext)只是用来存储您需要的变量的简单固定器。它是一个空对象,您在其中可以任意添加属性,比如:
  1. self.getAppContext().userName = req.getParameter("userName")
复制代码


And in your pages you can access them easily, for instance:
在您得页面中访问起来也很容易,比如:
  1. <h1>;Hello, <%=ApplicationCtx.userName%>;!</h1>;
复制代码


You have to use the ContextContainers to store information! It is not a good idea to store your data directly in the Snakelet, Webapp or whatever other objects!
您必须使用ContextContainer 来存储信息!直接将数据存放在Snakelet,Webapp或其他对象中并不是一个很好的主意。

TIP: to avoid AttributeError exceptions when you're accessing attributes that have not been defined in the context, you can use getattr with a default parameter:
提示:如果您没有在context中定义属性,为了避免您访问这些不存在的属性所造成的AttributeError 异常,您可以使用getattr附加一个默认值:
  1. <h1>;Hello, <%=getattr(ApplicationCtx,"userName","unknown name")%>;!</h1>;
复制代码


TIP: the Application context is perfectly suited to store stuff that you want to have access to (from your Ypages/snakelets) during the whole application, such as utility classes or persistent variables. You can do this in the __init__ method of one of your snakelets, for instance. The Session context is very important: you can store stuff here that is associated with the user session (it is unique per user, and is removed when the user is no longer on the site).
提示:Application context使用来存储您可以在整个Application中都可以访问的数据,就像公有类或固定值。您可以在每一个snakelets的 __init__方法中来实现他。Session context是非常重要的:用来存储与用户session相关联的信息(对于每个用户唯一,当用户下线后销毁)。

The Request context is volatile and only exists during the processing of a single request. You can put values here that need to be displayed on the target page.
Request context 是可变的,他仅存在于处理单独请求的时候。您可以用它来传递你要在页面中显示的数据。

The Snakelet context is not very useful (its inside a single snakelet, you could use regular class attributes for the same purpose).
Snakelet context 不是经常使用的(它存在于单独的snakelet中,您可以使用 regular class attributes来达到同样的目的)。

Server Context (there is none)

The WebApp runs inside the server. You cannot access this server. This is due to security restrictions, and most interesting stuff is already accessible trough the other interfaces). Because of this, the 'largest' scope is the web app scope. You cannot exchange information with another web app by using context storage, for example. You can store things on the web app context and read them from other snakelets or Ypages, within the same webapp.
WebApp在server中运行。您不能访问server。这是由于安全限制,很多有趣的信息已经可以通过其他界面访问。因此,’最大’范围是指web app的范围。您在web app之间不能通过context交换变量。您只能在同一个web app中使用snakelet 或 Ypage 对数据进行操作。

TOP

Response object

Your snakelet gets the current request and response objects in the serve method, and you can do lots of stuff with them:

Scope: request


      Method
      description

      getOutput()
      get the response output stream (socket/file). Notice that if you set/change the encoding (see setEncoding, below) you have to call this method after that!
      得到响应输出数据流(socket/file)。请注意,如果您使用了set/change encoding 方法(见 setEncoding),您必须在它之后调用getOutput()。

      setContentType(type)
      set the content type (mime type) of the response (default is "text/html"
      设置响应的内容类型(默认 “text/html”)

      setContentDisposition(disposition)
      set the content disposition (RFC 2183) of the response; you can control downloads with this. For example: setContentDisposition('attachment; filename="foobar.txt"')
      设置响应的内容部署(RFC 2183);您可以用它来控制下载。比如:setContentDisposition(‘attachment;filename=”foobar.txt”’)

      setContentLength(len)
      set the content length (number of bytes of the response data). This is useful if you know the exact size of your response in advance. Note: you cannot use this together with a custom content character encoding! If you are 100% certain that you are providing the correct length in bytes (after the character encoding has been applied!) you can give a second parameter, "force=True" to set the length even if a custom encoding has been set. Note that the server often determines the correct content-length by itself. Only in the case of snakelets it's left to you.
      设置控制长度(响应数据的长度)。当您预先准确的知道响应数据的大小,这个方法就很有用。注意:您不能将这个方法和自定义的内容字符编码同时使用!如果您 100%确定您提供的字节长度是正确的(在对字符编码之后!)您可以给出第二个参数,“force=True”说明有自定义字符编码,无论有多少字节。服务器经常自己测定字符长度。只是以防万一。

      setEncoding(enc)
      set character encoding of the response ('UTF-8' etc). You usually are required to set a specific character encoding if your page contains characters that are not in the plain ASCII character set. Notice that you must call getOutput() after this method! Set the encoding first, and get the output stream object after that. Also, you cannot use setContentLength() anymore.
      设置响应字符编码(比如 UTF-8 )。假如您的页面中有非ASCII字符的特殊字符,您就需要使用这个方法。注意您必须在这个方法之后使用getOutput()!首先使用 encoding,然后得到输出数据流对象,您不能在这里使用setContentLength()方法。

      guessMimeType(filename)
      possible mime type for this file (string)
      允许模拟类型(string)

      setHeader(header, value)
      set a custom HTTP header
      自定义HTTP 头部

      getHeader(header)
      get a custom HTTP header previously set by setHeader, returns None if header wasn't set
      得到先前由 setHeader设置的HTTP头部,否则返回None。

      setResponse(code, msg="output follows")
      set the HTTP response code (int) and response message (string)
      设置HTTP响应代码(int)和相应信息(string)

      HTTPredirect(URL)
      send a HTTP 302 client-side redirect to the specified URL The URL can be absolute ("http://.../..." or relative to this host ("/.../..." server-side redirection/inclusion is done on the Snakelet interface.
      发送一个HTTP 302客户端重新定向到一个特殊的URL,这个URL可以是指向服务器端的绝对路径也或对路径。

      sendError(code, message=None)
      send HTTP error with specified HTTP error code (int) and message (string)
      用特殊的HTTP错误代码(int)和 信息(string)报告HTTP错误。

      getCookies()
      return cookies set for sending (Cookie.SimpleCookie object)
      得到正在发送的cookie(Cookie.SimpleCookie 对象)

      setCookie(name, value, path=None, domain=None, maxAge=None, comment=None, secure=None)
      Add a cookie that will be sent to the client. Be careful what you provide as path, when you don't specify it, a default path will be used, that can be quite different from what you expect (especially when you use internal page redirection).
      添加一个准备发送到客户端的cookie。请注意您提供的信息,比如 路径,当您没有指定路径,将使用默认值,这可能导致与您所预期的不同结果(特别是当您使用内部重新定向的时候)。

      delCookie(name, path=None, domain=None, comment=None, secure=None)
      Make the client browser delete the specified cookie. Be careful what you provide as path, if it isn't exactly the same as when you originally set the cookie, it won't be deleted!
      使客户端浏览器删除特殊的cookie。请当心您提供的路径,如果跟您先前设置的有细微的不同,cookie将不会被删除。

      kill()
      tries to abort the response connection.
      试图放弃响应连接。

TOP

Request Object

Your snakelet gets the current request and response objects in the serve method, and you can do lots of stuff with them:
从server方法中得到的request 对象可以使用的方法和属性:

Scope: request


      Method        description

      getServerSoftware()
              server software version (string)
      server版本(字符串)

      getSnakeletsVersion()
              snakelets version (string)
      snakelets版本(字符串)

      getServerIP()
              server IP address (string). Don't use it in an URL, this screws up the virtual hosting feature.
      server IP 地址(字符串)。请不要在URL中使用,这将扰乱virtual hosting 。

      getServerName()
      published server hostname (string). Taken from the current virtualhost that handles the request. Which can be different from the webapp's owning vhost, because of vhost aliasing. This server name is safe to use in URLs, the virtual hosting will work nicely.
      server 主机名(字符串)。从当前正在控制request的主机得到主机名。由于vhost混用,可以和webapp自有的主机名称不同。Server名称在URL中是安全。虚拟主机也会正常工作。

      getRealServerName()
      real (internal) server hostname (string)
      真实server 主机名(字符串)

      getServerProtocol()
      supported HTTP level (string, "HTTP/1.0"
      提供HTTP等级(字符串,”HTTP/1.0”)

      getServerPort()
      socket port of the server (int)
      server 的socket 端口(int)

      getRequestURL()
              the original full request URL (without hostname and port), for example: "/page/test.cgi?arg=34" Use with the getBaseURL method to obtain a complete URL.
      原始的请求URL(没有主机名和端口),比如:”/page/test.cgi?arg=34”,和getBaseURL一起使用可以得到完成整的URL.

      getRequestURLplain()
              like getRequestURL, but also without any query args. Use with the next method (getBaseURL) to obtain a complete URL without query args.
      和 getRequestURL差不多,但是不包括询问参数。

      getBaseURL()
      The base URL of the server. Example: "http://desertfish.xs4all.nl:9080"
      得到server 的基本URL ,比如:”http://desertfish.xs4all.n1:9080”

      getPathInfo()
              any additional URL path components after the snakelet URL. Example: when url is 'snoop.sn/foo/bar?arg=value', it returns "/foo/bar". (Note: this is always empty when you use a fnmatch URL pattern for your snakelet!) (this string is not url-escaped)
      任何在snakelet URL后面附加的URL路径组件。比如:当url是’snoop.sn/foo/bar?arg=value’,将返回”/foo/bar”。(注意,当您使用URL匹配符号的时候返回是空!)(字符串不是 url-escaped)

      getMethod()
      the HTTP method used ("GET" or "OST"
      HTTP使用的方法(”GET” 或 “POST”)

      getQuery()
      the query args of the URL, example: "arg=value&name=foo%21". (this string is still url-escaped)
      URL的询问参数,比如:”arg=value&name=foo%21”。(字符串是 url-escaped)

      getFullQueryArgs()
      all the query args including path info and command, example: "/zip/zap?delete&arg=value&name=foo%21" (note: this is not the full URL! You can get that one from the Snakelet) (this string is still url-escaped)
      得到所有询问参数的路径信息和指令,比如:”/zip/zap?delete&arg=value&name=foo%21”(注意:这不是完整URL!您可以从Snakelet中得到)(字符串为  url-escaped)

      getRemoteHost()
      hostname of the remote host (string)
      远程主机名(字符串)

      getRemoteAddr()
      IP address of the remote host (string)
      远程主机IP地址(字符串)

      getRealRemoteAddr()
      the 'real' IP address of the remote host (use this if you are running via Apache Proxy module)
      远程主机真实IP(如果您使用Apache Proxy 模块,就需要使用这个方法)。

      getContentType()
      the content-type of the request (string)
      得到请求内容类型(字符串)。

      getContentLength()
      content length of the request (int)
      请求内容长度(int)

      getUserAgent()
      browser ID string of the client's browser, or '' (empty string)
      客户端浏览器的ID,或 ‘’(空字符串)

      getReferer()
      the referring URL (that is: the url we came from), or '' (empty string)
      询问URL(就是我们从哪个url来访问的),或 ‘’(空字符串)

      getCookie()
      raw cookie information (comma separated string)
      cookie 信息(逗号分割的字符串)

      getCookies()
      parsed cookies (mycookie.SimpleRequestCookie object, this is a dict, which maps cookie names to a list of string values)
      分析过的cookies(mycookie.SimpleRequestCookie 对象,将cookie名称字符串值映射到一个 列表)

      clearCookies()
      erases all cookie information from the request (not from the client!)
      从请求中清楚所有cookie信息(不是从客户端!!)

      getInput()
      request input stream (socket/file)
      请求输入流(socket/文件)

      getArg()
      URL argument. Example: when url=snoop.sn?command&arg=name it returns "command" (this string is not url-escaped)
      URL参数,比如:url=snoop.sn?command&arg=name,将返回”command”(字符串不是 url-escaped)

      setArg(arg)
      reset the URL argument (getArg() ) to something new.
      重新安排URL参数。

      getWebApp()
      the current WebApp object
      得到当前的 WebApp对象

      getRangeStr()
      the unparsed string value of the HTTP 'range' header, or '' (empty string).
      没有分析的HTTP ‘范围’头部字符串值,或’’(空字符串)。

      getRange()
      the parsed HTTP 'range' header; a tuple: (from,to)
      分析HTTP’范围’头部。

      getAuth()
      the HTTP Authorization header value, or '' (empty string).
      HTTP认证标头值,或 ‘’(空字符串)

      getAllHeaders()
      all HTTP headers (mimetools.Message object)
      所有HTTP头部(mimetools.Message 对象)

      getHeader(header)
      value of specified HTTP header, or None if it isn't present
      指定HTTP头部值,如果不存在为None。

      getForm()
      parsed form contents (a dict of {param name: value} ) The form has a utility method urlencode() that returns an url-encoded query args string like "arg=value&foo=bar" for the form's parameters.
      分析标单内容,可以使用urlencode()方法返回从form中得到的参数的url编码的询问参数字符串 如 “arg=value&foo=bar”。

      getParameter(param, default='')
              value of a single form parameter (or the provided default value -which is an empty string if not otherwise given- if the parameter doesn't exist)
      单独的参数值(或者提供的默认值)。


      setParameter(param,value)
      sets the new value of a form parameter (as if this value was filled in by the user). See also getContext() below!
      为标单参数设定新值。见getContext()

      getContext()
      request context (ContextContainer object). Scope: request. unique per user and per request, destroyed after request completes
      请求关系(ContextContainer 对象)。范围:请求。一个用户对应一个请求,当请求完毕立即销毁。

      getSession()
      the session object (snakeserver.snakelet.Session object), None if there is no sessionsession
      对象(snakeserver.snakelet.Session 对象),如果没有session返回None。

      deleteSession()
              logout current user and deletes the session object. Also clears all cookie info on the request (not on the client!)
      登出当前用户并销毁session对象。同时也清除请求中的cookie信息(并不是客户端的cookie!)

      getSessionContext()
      the session context (ContextContainer object). Scope: session. unique per user, shared for all requests of this user. None if there is no session.
      sesscion 关系(ContextContainer 对象)。范围:用户唯一session,共享请求。如果没有为None。

      getMaxPOSTsize()
      the current max size of a POST request (in bytes)
      当前最大POST 请求数据量(byets为单位)

      setMaxPOSTsize(numbytes)
      set the maximum size in bytes of a POST request (default: 200000=200Kb). If it is larger, the server aborts the connection and the POST request fails, and a FormFileUploadError exception is raised.
      设置最大POST数据量(默认 200000=200Kb)。如果超过最大值服务器将放弃连接,POST请求失败,产生FormFileUploadError。

      getEncoding()
      the current request character encoding. None if not specified (means default).
      当前请求字符编码。如果没有指定,则为None(默认).

      setEncoding(encoding)
      forces the request character encoding. This is often necessary to correctly read non-ASCII characters from From Posts. Also note that form fields will be unicode strings (instead of regular strings) if you set the encoding.
      强制字符编码。当碰到非ASCII编码的表单传送时是非常必要的。




Getting request parameters is done using getForm(), or getParameter(). You can (re)set a parameter for the duration of the request using setParameter(). You can clear all parameters for the duration of the reqeuest using getForm().clear() - because it is just a dict.
可以使用getForm()或getParameter得到请求参数。可以通过setParameter()设置参数。可以通过getForm().clear()清除所有参数。

TOP

Getting the URL prefixes, easy URL creation

In Ypages you have some shortcuts to easily obtain the current URL prefix and so on. From a Snakelet, you can do exactly that but not directly: you have to get the webapp first using getWebApp() and use its methods instead. The webapp object also has two convenient methods to create urls: mkUrl and mkAssetUrl!
在Ypage中有一些很方便的捷径来获得URL前缀。对于Snakelet,您可以或者前缀,但是没有这么直接:您必须先使用getWebApp()得到webapp。Webapp对象有两个很方便的方法用来创建url:mkUrl 和 mkAssetUrl !


Using self in Snakelets to store data

Short: you shouldn't. Long: your Snakelet code has no single, local, 'personal', environment it is running in. There is only one object (instance) of your Snakelet and it might be accessed concurrently by multiple threads. Only use local objects to store temporary data in, never create new properties on self! If you really need to store some data that is local for this Snakelet, and shared for all users and all requests, you can use the getContext() method to obtain the local Snakelet data context.
您的Snakelet代码不能在单独的,独立的,’个人’的环境中运行。这里只有一个Snakelet对象,他们可能同时被多个线程访问。仅仅使用本地对象来存储临时数据,但并不在self上创建新的属性!如果您想存储并共享本地数据和所有请求数据,您可以使用getContext() 方法获得当前Snakelet数据。

Making a download snakelet that serves static file content

Use self.getWebApp().serveStaticFile(filename, response, useResponseHeaders=False) to utilize the server's own internal code to serve static files efficiently. See the webapp chapter.
使用 self.getWebApp().serverStaticFile(filename, response, useResponseHeaders=False) 来利用server内部自有代码有效的提供静态文件服务。见webapp章节。

TOP

Snakelet class

Your own snakelets have to subclass from the generic Snakelet class and thus inherit all methods from that class. You can use the following methods of the Snakelet base class:
您自己的snakelet类是从一般的Snakelet类中继承来的,因此也继承了这个类的所有方法。您可以使用这些基本的方法:


      Method方法          Description描述
      serve(request, response):
      must override this to handle requests, the parameters are the request and response objects.
      必须重载这个方法来处理请求,参数是 request 和 response对象

      getWebApp()
              the current WebApp object. Contains additional interesting methods.
      当前的WebApp对象,包含附加的有趣的方法(???)。

      getContext()
              snakelet context (ContextContainer object). Scope: snakelet. shared for all users/requestssnakelet关系(环境?)(ContextContainer对象)。
      范围:snakelet。对所有的用户/请求 共享。

      getAppContext()
              webapp context (ContextContainer object). Scope: web app. shared for all users/requestswebapp 前后关系 (ContextContainer对象).
      范围:web app。对所有用户/请求 共享。

      getPlugin(pluginname)
              look up the (running) plugin object by its name (raises KeyError if not found)
      查询(正在运行的)plugin对象,其名称作为参数(如果没有找到产生KeyError)。

      getPluginNames()
              a list of names of the installed plugins
      已经安装的plugin 名称列表

      getFullURL()
              returns full URL of this snakelet (without query args). if you are using URL patterns, this cannot be used in that snakelet! (because the pattern ends up in the URL) Example: "http://desertfish.xs4all.nl:9080/test/snoop.sn" NOTE:The hostname in the url is the virtual-host-name from what Snakelets thinks is the vhost for this request. If you are running Snakelets behind a proxy (and/or the bindname is different), this hostname may not be correct! The solution is to enable the Vhost config and to define a correct virtual-host mapping for the 'real' hostname. You can still use a different bindname, if you wish.
      返回当前snakelet的完整URL(不包括参数)。如果您使用URL样式,这将不能再snakelet中使用!(因为URL结尾的样式)例如:”http://deserfish.xs4all.n1:9080/test/snoop.sn” 注意:在url中的主机名是虚拟主机名。如果您正在使用代理方式(或者  bindname不同),这个主机名可能就是不正确的!解决方法是打开 Vhost选项定义正确的虚拟主机映射真实主机名。如果您希望,您仍然可以使用不同的bindname。

      getURL()
              server-relative URL pattern of this snakelet or Ypage, example: "/test/snoop.sn" If you use a URL pattern for your snakelet, that pattern is returned (example: "/test/*.pdf"! So it is not safe to use this method for constructing URLs. Use the getRequestURLplain method of the request object instead! If you are not using URL patterns, you're safe. For Ypages with a form this is useful if the form should be posted to the page itself, you can then easily do <form action="<%=self.getURL()%>;" .... >;
      snakelet 或 Ypage 的相对URL路径样式。比如:”/test/snoop.sn” ,如果您为您的snakelet使用URL式样,就会返回式样(如: “/test/*.pdf”)!所以使用这种方法构造URL很不安全。使用request  对象的 getRequestURLplain 方法代替!如果您没有使用URL式样,那么就是安全的。对于Ypage,用这个方法来传送表单是很方便的:<form action=”<%=self.getURL()%>;”…>;

      init()
              override this to perform custom initialization at load time
      重载这个方法,当加载的时候执行自定义的初始化。

      getDescription()
      override to return a description string for the snakelet
      为snakelet返回描述字符串

      requiresSession()
              override this to return one of the special SESSION_* values defined in the Snakelet class (for instance return self.SESSION_WANTED), that signify what kind of session is required. Also see the session Ypage-declaration below. The possible values are: SESSION_NOT_NEEDED (no session and session cookie), SESSION_WANTED (use session and session cookie), SESSION_REQUIRED (requires a synchronised session), SESSION_LOGIN_REQUIRED (requires a session with a logged in user), SESSION_DONTCREATE (use existing session, if available, if not: do NOT create a new session). If you use the last one and you do not provide a means of user-authentication (see getAuthMethod below), Snakelets will return a 403-error page when you try to access the page if you are not logged in.
      返回在Snakelet 类中定义的特殊 SESSION_* 的值(比如返回self.SESSION_WANTED),见下文的 session 的 Ypage声明。可能存在的值:SESSION_NOT_NEEDED (没有session 和 session cookie),SESSION_WANTED (使用session 和 session cookie), SESSION_REQUIRED (请求同步session),SESSION_LOGIN_REQUIRED(请求已经登陆的用户 session),SESSION_DONTCREATE(如果已经存在的session,使用这个session,如果没有也不另外创建新的)。如果您使用最后一个并且您没有提供用户验证的方法或手段(见 getAuthMethod),当您在没有登陆的情况下试图访问页面,Snakelets将返回 403-error 页面错误

      getAuthorizedRoles()
              override this to return a list or set of privilige names that are allowed to access this snakelet. Default is None (no access control).
      返回可以访问snakelet的特权名称列表或者设置列表。默认是None。

      getAuthMethod()
              override this to return a tuple (method,argument) that defines the authentication method to use for this snakelet. See authorization.
      返回一个定义了验证方法的数组。

      allowCaching()
              override this to return True if the browser is allowed to cache the page, False otherwise. Default is False.
      如果浏览器允许页面缓存,返回True ,否则返回False。

      escape(str)
              escapes a string to make it HTML-safe (< becomes & etc)
      字符串转换,使HTML更安全(特殊符号转换)

      urlescape(str)
              escapes a string to make it URL-safe (spaces become '+', ? and & are translated etc). Don't use this on full URLs with URL query args, because it escapes the characters that must be there to separate the args. It is intended for the value strings for those args.
      URL字符串转换(空格 转换为 ‘+’ ,? 和 & 被解释)。不要在带有URL参数的完整URL中使用它,因为escape字符必须对这些参数进行分割。他是打算为 字符串值 设置的。

      urlunescape(str)
              un-escapes an url-escaped string. Only use this for URL component strings, not on whole URLs!
      反编 urlescape 字符串。只为 URL片断服务,不能用于完整URL。

      redirect(URL, request, response)
              internal redirect to anoter URL ( "http://..../.." or "/webapp/page.y" ) Note: new URL query args are NOT parsed! Set them with request.setParameter
      内部重新定向其他URL(”http://…/..” or “/webapp/page.y”)注意:新的URL询问参数是不会被解析的!使用request.setParameter对他们进行设置。

      include(URL, request, response)
              internal include of another URL ( "http://..../..." or "/webapp/page.y" ) Note: new URL query args are NOT parsed! Set them with request.setParameter
      内部include其他URL(“http://…/..” 或 “/webapp/page.y”)注意:新的URL询问参数不会被解析!需要使用request.setParameter来设置他们。

      getErrorPage()
              the URL of the currently defined custom error page, or None.
      当前自定义的error 页面。

      setErrorPage(URL)
              set a custom error page (URL string) that must be shown -instead of the faulty page- when an unhandled exception occurs in this snakelet. See the "errorpage" declaration for more details on the data available to you in your custom error page.
      设置自定义error页面(URL 字符串),当一个不受控制的错误产生的时候必须设置自定义错误页面来代替不完善的页面。更多error页面信息请见 “errorpage” declaration

TOP

Character encoding: almost a non-issue

With other web servers, the correct handling of non-ASCII characters or symbols often is a pain. Not with Snakelets. You only have to set the output encoding of your page to the desired encoding (such as UTF-, and optionally set the input encoding too (if your source file is written in a special character encoding), and Snakelets takes care of all the rest. Don't encode stuff yourself, just write those unicode strings to the page output! If you are careful about the way you add FORMs to your pages (see below), the input of special characters is painless too. Snakelets handles everything and you get to deal with Python strings (or unicode objects) only. All symbols are supported. The suggested character encoding is UTF-8 (it can contain all symbols, is widely supported, and works efficiently for most western languages). You can define a character encoding in every page or define one global setting for all pages using the webapp's defaultOutputEncoding config variable.
在其他web server中,正确处理非ASCII字符或者符号是非常痛苦的。在Snakelet中不需要这样。您只需要要求您页面的输出编码(比如 UTF-8),随意的设置输入编码(如果您的源文件使用特殊字符编码编写),Snakelet将会很好的照顾这些编码。不要自己进行编码,只需要在页面中写入unicode字符串!如果您正在考虑FORM的输入表单,输入特殊字符页是没有问题的。Snakelet会处理所有这些字符,您只需要提供 python 字符串(或者 Unicode 对象)。

Content-type

Usually the default content type text/html is fine. But for special snakelets or Ypages you are not returning HTML, but a different file type (when you have created an image downloading snakelet, for instance). You have to specify the correct content type yourself in these cases.
一般默认内容类型是 text/html。但是对于特殊的snakelet或Ypage除了不同的文件类型以外您不能返回HTML(比如您创建了一个图片下载snakelet页面)。您需要自己指定正确的内容类型。

....write how to do this... defaultContentType....
。。。如何实现。。。defaultContentType...

FORM handling
...not yet written...
...还没有写...

TOP

Building correct URLs, independent of server and webapp name

建立正确的URL,不依赖于server和 webapp名称

Generating correct URL links on your page is not a trivial task, if you want your page code to be independent of the server name, port, webapp name, prefix and whatnot. URLs have the form: http://server:port/serverprefix/webapp/... (serverprefix is optional). If you only use relative urls (such as <a href="sub/page.y">;....) you don't have to worry about the url base part because the browser fills it in. But usually it is better to use an absolute url (in a menu, to avoid nesting issues) or even an url that includes the http: part, and the servername and port. You can hardcode these values in your pages but then they cease to work when you move to a different server or rename the webapp...
为您的页面建立正确的URL并不是简单的任务,如果您想让页面代码不依靠server名称,端口,webapp名称,前缀。URL是这种形式:http://server:port/serverprefix/webapp/…(server前缀是可选的)。如果您只是用相对url(如 <a href=”sub/page.y”>,那您就不用担心url的基本部分,因为浏览器会自动添加。但是通常最好使用绝对路径(在菜单中,避免嵌套)或者包括 http: 部分的url,和 servername 以及port。您可以将这些数据固定到页面中,但是当他们被改名或者移动到别的webapp中的时候就不能正常工作了。


      Relevant functions相关函数

      Ypage:
      These are shortcuts to functions defined elsewhere (see the column to the right) to make it easier to use inside an Ypage:这是使用被定义的function的捷径,使得他们在Ypage中使用起来十分容易:
  1. self.URLprefix
  2. self.Assetprefix
  3. url(path)
  4. asset(path)
复制代码


for Ypages and Snakelets:
Defined on the Snakelet/Ypage class:在Snakelet/Ypage class中定义的 :
  1. self.getFullURL()
  2. self.getURL()
  3. self.urlescape(str)  # see above, at 'escaping'
复制代码


Defined on the Webapp: 在webapp中定义的:
  1. wa.getURLprefix()
  2. wa.getAssetprefix()
  3. wa.mkUrl(path)
  4. wa.mkAssetUrl(path)
复制代码


Defined on the Request object: 在request object中定义的:
  1. req.getRequestURL()
  2. req.getRequestURLplain()
  3. req.getBaseURL()
复制代码


      And perhaps some more (see relevant chapters) 还有其它的(请见相关章节)


...explanation not yet written...
...解释说明还没有写...

TOP

本帖最后由 Perl 于 2012-2-22 21:17 编辑

Other ways of avoiding page code duplication, and structuring your page code

Another possibility is to put parts of a page that are used over and over again inside a separate Ypage that is not accessed directly. Rather, you include it inside other Ypages that want to use it. For instance: if you find that you are building a complicated table structure on several different pages, you can put the table code in a separate Ypage file and include it in the other pages. If you want to change the table, you only have to make changes in one file, and the table is changed on all pages.
另外一种可能性就是 页面的一部分在单独的Ypage中被重复使用,而且不能直接访问(在其他页面中使用你想要使用的页面的某一部分?)。相当于你将你想用的部分 include到其他Ypage中。比如:您发现您正在很多不同页面中建立一个复杂的表格结构,您可以将表格代码放到一个单独的Ypage文件中,在其他页面中include它就可以了。如果您想修改table您只需要修改一个Ypage文件,而不需要做大量修改工作。

A more advanced way is to use inheritance to let your Ypage inherit from another Ypage or even from a custom Python class. You can put common code in the base Ypage or class and let multiple pages inherit from it, so that they will share the code. It is possible to let the base Ypage handle the page creation (and refer to the inherited page) by using the pagemethod declaration.
更高级的方法是 继承,也就是使你的Ypage继承其他 Ypage或者其他的python 类。您可以将公共代码放到基本Ypage或者 class中,然后让其他页面继承他们。通过使用pagemethod声明可以让基础Ypage控制页面创建。

Ypages and Snakelets are essentially just Python classes so you an import and use other modules and classes just like you would otherwise do to structure your Python program. Put common code and/or code that is not related to the actual page content in a different module, and import that in your Ypage/Snakelet, so that the rest of the code can stay concise and clean. Use subdirectories to divide and group related pages (just as you would use packages in regular Python code).
Ypage和 Snakelet 基本上是Pyhton 类,所以您可以像编写Python程序一样调用module或者 class。可以在与正是页面无关的module中编写公共代码/代码,并通过import来引用到您的 Ypage/Snakelet中,这样编写代码十分简洁。使用子目录来分离和聚合有联系的页面(就像在python中使用package)。

HTML- and URL-escaping

Some characters are invalid inside HTML (such as <, >;, & and ". If you generate HTML, you have to make sure that you escape (also called quote) those special characters. You should use the self.escape(text) method for this. Escaping is only needed at the place where you actually want to output the text on the page.
一些字符在HTML中是无效的(比如 <, >;, & , “)。如果您生成一个HTML,您必须确定您将这些特殊符号escape(也叫 引)起来。您可以使用self.escape(text)方法来实现。Escaping 只需要放置你在页面中想要输出的文本。

The same counts for URLs. There are a few other characters that cannot occur in an URL because they have a special meaning (/, +, ? and = for instance). If you need to put those in an URL where they do not have that special meaning (for instance, where they are part of the URL query params in case of a GET request with params), you have to escape them. You should use the self.urlescape(path) method for this. Note that the URL-escaped string may be a valid URL, but it may still contain characters that are invalid in HTML! So if you want to place it inside your page text, you usually have to run it trough the HTML escape function before outputting it on the page.
对于URL也有同样的问题。有一些符号是不能在URL中出现的,因为这些符号有特殊含义(/, +, ? 和 = )。如果您想把他们放到URL中(比如他们是参数的一部分),您必须使用self.urlescape(path)方法 escape他们。注意URL-escape 字符串是合法的URL,但是它仍然可以包括非法的HTML字符!所以您要想将这些文本放到页面中您就需要通过执行HTML的escape函数输出他们。

TOP

Effective Ypages and Snakelets

This chapter is a tutorial about creating effective and maintainable web pages. The following subjects are covered:
这一章是关于如何建立有效持久web页面的指南。包括下面几个条目:


      ·        Ypage templating (???模版化?)
      ·        Other ways of avoiding page code duplication (避免页面代码复制的其他途径)
      ·        HTML- and URL-escaping (HTML 和 URL 编码???)
      ·        Building correct urls (建立正确的url)
      ·        Character encodings  (字符编码)
      ·        Content-type (内容类型)
      ·        FORM handling (表单控制)



For details on the different subjects, you must read the other chapters in this manual. This chapter is a summary to get you started quickly.
详细资料您需要阅读参考手册的其他章节。这一章只是概要。

This text is not yet finished, it will be more detailed in a future version
这一部分还没有完成,在以后版本中将会补充新的内容。

Ypage Templating and Inclusion

To avoid repeating parts of your page code over and over again in each page you should define the general layout and common parts of your pages in one or more template pages. All your other Ypages can then just contain the template declaration, and only the page content that is different in each page. The template page could define a common header, menu, body layout, footer and script/css links, and the rest of the pages only define the body content. If you want to change the layout of the site you only have to update the template and all your pages will use the new layout. You can define a template page in every Ypage or define one global template for all pages using the webapp's defaultPageTemplate config variable.
为了避免您在网页中一遍又一遍的使用同样的代码,您应该创建 一般布局和公共部分或者创建模板页面。其他 Ypage页面只需要包含模板声明就可以了,页面中只包含自己需要的内容就可以了。模板页面中可以声明公共header,菜单,body框架,页脚 和 script/css 连接,其他页面只需要定义 body中的内容。如果您想更改body框架,您只需要更新您的模板页面框架就可以了。您可以在任何一个Ypage中定义 模板页面,也可以对webapp的defaultPageTemplate进行设置来为所有页面定义全局模版。


As a template page is just an Ypage, you can do all sorts of dynamic page creation code inside it. It is even possible to pass page-specific variables from every templated ypage into the template page, so that you may use that in the template (example: to give every page a page-specific title, where the title is defined in the templated page). These template args can be simple and static, or dynamically created using a special page method.
模板页面和 Ypage一样,您可以在其中插入任何动态页面创建代码。当然也可以传送 page-specific (页面指定) 参数从一个模版 ypage到另一个模板页面,以便您在模板中使用(例如:为每一个页面添加一个以近改模板中定义了的 page-specific 名称)。这些模板参数可以是很简单的,静态的或者被特殊页面方法创建的动态参数。

TOP

Smart Suffix Search

Snakelets also uses a 'smart suffix search'. This means that it is not strictly required to have the correct file suffix in the URL. This allows for 'cleaner' URLs. If a page is not found, Snakelets will try again by -internally- appending the .y, .html and .htm suffixes (in that order). For instance, http://server.com/testapp/office/login.y will load the "login.y" Ypage, but so will http://server.com/testapp/office/login (the same url but without the .y suffix). Notice that dynamic content has higher priority than static content, so if "login.y" and "login.html" both exist, the server will use "login.y". This mechanism is rather useful when you are setting up a website: you can start with all static .html pages, and replace them later on with dynamic .y pages - without changing any of your URLs.
Snakelets 使用了 ‘ smart suffix search ‘。就是说在URL中的文件后缀不一定严格准确。这允许使用 ‘cleaner’ URL。如果页面没有找到,Snakelets将逐个搜索 .y, .html 和 .htm 后缀。比如 http://server.com/testapp/office/login.y 将载入 ‘login.y’页面,同样将搜索除 .y 后缀以外的 http://server.com/testapp/office/login文件。注意动态内容比静态内容有更高的优先级,当 ‘login.y’ 和 ‘login.html’同时存在时,server将优先使用 ‘login.y’。这种机制是很有用的:您可以先使用静态.html页面,之后用动态 .y 页面代替 --- 而不用修改任何URL连接。

There is one small issue: the 'smart suffix search' does not work if you are using path components in the URL query parameters. For instance, http://server.com/testapp/office/login.y/floor1 will work (it will call login.y with "/floor1" pathinfo on the request), but http://server.com/testapp/office/login/floor1 will not work. (If you want something like this to work, use a Snakelet with a suitable URL pattern). Note that regular query parameters do work: http://server.com/testapp/office/login?floor=1 works fine (it will call login.y with correct query parameters).
这又一个小小的问题: 在您使用路径作为参数的时候‘smart suffix search’是不工作的。比如: http://server.com/testapp/office/login.y/floor1 工作(这将传递给login.y ‘/floor1’路径信息,而 http://server.com/testapp/office/login/floor1不工作。(如果您想使这样的方式正常工作,需要适当的设置 URL标记)。注意:http://server.com/testapp/office/login?floor=1 也是可以很好工作的(这将传递给login.y正确的参数)。


Smart suffixes and authorization patterns: when checking authorization patterns, Snakelets takes smart suffixes into account. For more info see authorization.
后缀 和 认证标记:当验证认证标记的时候,Snakelets将后缀考虑在内。更多信息参考 authorization.


Automatic reloading
For fast development, Snakelets supports automatic page reloading. This means that when you update an Ypage source file, or a Snakelets module source file, the server will detect that it has been updated and it will reload and recompile the new version. This happens on-the-fly so you will directly see the changes you have made in your browser.
为了实现快速的开发,Snakelets  提供自动页面重载。当您更新了您的 Ypage 文件,或者 Snakelets 模块文件的时候,server会自动监测您的更新,并且自动载入新版本的文件。所以您可以很方便的直接看到您修改的结果。

To avoid problems and performance issues, the automatic reloading is limited to the Ypage source file (and templates, if any) and the snakelet module file. Imported modules are not reloaded.
为了避免错误,自动重载功能只对 Ypage 源代码文件和 snakelet module文件有效,被import 的 module文件不会被重新载入。

Page Creation Tutorial

Please refer to Effective Ypages and Snakelets for a tutorial on creating good, maintainable web pages.

TOP

本帖最后由 Perl 于 2012-2-22 21:18 编辑

Create pages for the web application

Let's say that you have created a web application "testapp" and that it has a "docroot" directory where you will put your page files, so you must point the docroot attribute to it in the webapp's init file, as described above. The files in that directory will now be accessible in your browser by using the url base: http://server.com/testapp/
加入您创建了一个web应用程序”testapp”,在此目录中有一个 “docroot”目录用来仿制您的页面文件,您必须在webapp的 init文件中指定docroot属性,就像我们先前描述的。该文件将不能通过url访问:http://server.com/testapp/

Snakelets maps the rest of the URL to the filesystem (=the contents of the docroot directory) in a rather straightforward way, much the same as a normal web server such as Apache does this. A path component in the url maps to a directory on disk, and a file component usually maps to a file on disk. So that means that when the url http://server.com/testapp/office/page.html is requested, Snakelets will return the "page.html" file from the "office" directory in the docroot location. For Ypages it is the same, http://server.com/testapp/office/login.y will cause Snakelets to load and run the "login.y" ypage in the given location.
Snakelets 直接将URL映射到系统文件(=docroot 目录的内容),跟Apache一样。每一个路径组成部分都映射到硬盘上的某一个文件夹,文件映射到硬盘上的文件。所以,当 http://server.com/testapp/office/page.html被请求的时候,Snakelets将从docroot的 office目录返回 ‘page.html’文件。对于Ypage也是同样。

It is impossible to request files outside the docroot location this way. That is nice, because you can protect your other files (web app source code and such) very easily just by placing them in a different directory as your web pages. You could fool around with the documentAllower function but this is more convenient and faster.
这种方式不可能请求到docroot区域以外的文件。这样你可以很容易的保护其他文件(比如 webapp的源文件代码),只要你把他们放到其他目录。您可能会随意的使用 documentAllower函数,但它确实方便,快速。

There is a big exception to the simple URL-to-filesystem mapping: Snakelets. Dynamic content created by a snakelet page is not found on disk in the regular way. Instead, there is a snakelet object defined in your Python source code that is called by the server when a URL is requested that triggers the snakelet. Which URLs trigger which snakelets, is configured in the "snakelets" attribute in your webapp init file (see above). Because you can use simple wildcard patterns there, a lot of URLs may be mapped onto a single snakelet object.
在URL到系统文件的映射问题上有一个例外:Snakelets。被snakelet 创建的动态内容在硬盘上是着不到的。他是定义在你的python源文件中的对象,当URL被请求的时候server会调用他从而触发snakelet。哪一个URL触发哪一个snakelets,这都定义在您的web app 的 init(初始化)文件中(见前面文章)。因为您可以使用通配符号,所以大部分的URL可以映射到单一的snakelet对象。

The server uses the following order to determine what is returned for a requested URL:
server 返回下面几种URL请求:


      1.        Snakelet url/patterns
      2.        Dynamic page (Ypage)
      3.        Static page/file (.html etc)



Index pages
When you leave out a specific page name from an url (example: http://server.com/app/info/) the server will try to fetch the index page for that directory. If there is a file index.html (or index.y) in that location, Snakelets will load that one. It is as if you typed the url http://server.com/app/info/index.y.
See above at the indexPages variable what the default list of files is that are searched for, and how you can change this.
当您没有对url指定页面名称的时候(如:http://server.com/app/info/)server就会自动尝试此目录中的 index 页面(或 index.y)。和使用url http://server.com/app/info/index.y。如何设置默认页请见前面文章。

Snakelet as index page: if no other suitable page is found, the server will also try to use a Snakelet as index page. You have to configure a snakelet with a suitable URL pattern to make this work. The server looks for index.sn Snakelet in the requested URL path, so when the URL "http://server.com/test/dir/" is requested and you have configured a snakelet in the "test" webapp on the pattern dir/index.sn or */index.sn it will be used as index page. You can also use a Snakelet as 'root' index page in your webapp, but you will have to add it explicitly to the Snakelet list (because of the way the fnmatch urlpatterns work): use the pattern index.sn (no pre- or suffixes).
To avoid conflicts with other snakelets, it is required that the url pattern for your index snakelet(s) explicitly ends in 'index.sn'.
Note that you can create 'fake' directories using index Snakelets; the directory that you use in the snakelet url path pattern doesn't have to exist on disk - in contrast to regular index pages.
Snakelet 作为index page:如果没有找到匹配的页面,server就会尝试使用snakelet 作为索引页面。您必须对snakelet的url标记进行设置才能正常使用此功能。 Server会自动在请求路径中寻找 index.sn ,但是这需要您明确的指出:使用标记 index.sn 。为了避免冲突,url标记必须以 ‘index.sn’结尾。注意 您可以使用index Snakelets创建一个“冒牌”的目录;这个目录并不一定在硬盘上存在 --- 同正规页面有鲜明的对比。

TOP

本帖最后由 Perl 于 2012-2-22 21:11 编辑

Creating a Web Application

The web application that you will be making is essentially a lot of files in one or more directories. Static content files such as html files and images, dynamic content files such as Ypages, and web application code itself (python source code files). This chapter shows how they all fit together.
我们创建的web 应用程序基本上都是有很多文件或者文件夹组成的。静态页面包括html和图片,动态内容一般都是Ypage,还有web应用程序本身代码(python源代码文件)。这章将阐述它们之间是如何协调工作的。

FIrst you have to create and configure your web application, and then you must fill it with web pages.
首先您应该创建并配置您的web应用程序,之后添入我们需要的页面文件。

Setting up the web application

Put your stuff in a Python module in the "webapps" directory. The directory (module) name is also the name and URL context name of your web application. So when your webapp is in a directory called store, it will be accessible with the URL http://server.com/store/ There is one special reserved name: if you have a web app named "ROOT" that one will be used as the web application for the root context '/'. (When you are using Virtual Hosting settings, you can change this, it is only used when no vhosts are defined).
将您的源文件放到 webapps目录中。这个目录(模块)的名称跟您的web 应用程序的URL 名称相关。如果您的webapp被存储到文件夹 store中的时,您就可以通过http://server.com/store/ 来访问他,这里还有特殊的保留目录名:ROOT,相当于web 应用程序的根目录 ‘/’。(当您正在使用虚拟主机时,您可以对其进行修改,当没有定义vhosts的时候可以使用他。)

The module's __init__.py must contain the configuration settings for your web app:
模块 __init__.py 包括如下配置内容:


      Attribute属性        Description描述

      name        The descriptive name for this webapp
      webapp的描述名称

      docroot        The (relative) directory where files are served from, usually "." (which means the directory of the webapp itself). Many webapps also choose to use "docroot" or something similar, and then put all files into a docroot/ subdirectory. This is a bit more secure because it is not possible to access files outside this directory, so you can place code or other data in the webapp directory without worrying about this.
      文件服务目录(相对目录),一般为 ‘.’(webapp的目录从属关系)。一般的webapp都使用 “docroot” 或者类似的名称,并将所有文件放到docroot/ 的子目录中。这是比较安全的,因为外部不能访问此目录中的文件,所以您可以比较放心得将您的代码或者是数据存放到此目录中。

      assetLocation        The (relative or absolute) url location where static assets are to be found. If you use a relative location ("static/img/" for instance), the assets are located inside the webapp's docroot (use "." to use the docroot directory itself, instead of a directory inside it). If you use an absolute location ("/static/" for instance), the assets are located in another web app or path entirely (but still on the same web server). It is also possible to put a totally different url here such as "http://images.server.com/img/" to be able to serve static assets (images, files) from an entirely different server. This setting is used by the asset Ypage function and the mkAssetUrl Webapp function.
      可以访问到静态文件的url路径(相对 或 绝对)。如果您使用相对路径(比如 “static/img/”),所有文件都被放置到 webapp的docroot中(可以通过 ‘.’来使用docroot目录)。如果使用绝对路径(”/static/”),所有文件将被放到其他的 web app或者路径中(但是仍然使用同一个 web server)。也可以将文件(图片,文件)放到完全不同web server的url中,比如 http://images.server.com/img/ 。设置此项可以通过 asset Ypage函数 和 mkAssetUrl Webapp函数。

      snakelets        a dict that maps (relative) URL patterns to snakelet classes. With this you define the snakelets in your web application, and on what URLs they are 'listening'. Don't forget to import the required modules/classes. You can use 'fnmatch'-style patterns here, for instance: docs/*.pdf would let the snakelet listen on any URL that matches this pattern, such as http://.../docs/report.pdf (the full URL must match the pattern). If you don't use a pattern, any URL that starts with the string matches. Note that if you use fnmatch-patterns, you cannot use path info arguments anymore (only query args): http://.../docs/report.pdf/path/info?foo=bar doesn't work, but http://.../docs/report.pdf?foo=bar still does. See below how you can use Snakelets as virtual index pages.
      映射(相对) URL 式样到 snakelet classes(这句话如何翻译?)。您可以在您正在使用的web应用程序中定义snakelets,让它通过URL来监听您的web 应用程序。不要忘了 import 需要的 模块/类 。在这里您可以使用 ‘fnmatch-style 式样。比如:docs/*.pdf 它可以让snakelet任何URL上与之相匹配的式样。像 http://…/docs/report.pdf(完整的URL必须匹配式样)。如果不是用式样,URL将使用 字符串 匹配。请注意如果您使用 fnmatch-pattens ,您将不能使用 path info 参数(只是query参数):http://…/docs/report.pdf/path/info?foo=bar 是不能工作的,但是http://…/docs/report.pdf?foo=bar 仍然工作。详细请见下文 如何真正的使用Snakelets.

      configItems        a dict that you can fill with any config items you want to be available in the web app trough the getConfigItem() method.
      通过getConfigItem()方法在web app中设置您想使用的配置项目。

      sessionTimeoutSecs        the inactivity period it takes for a user session to be deleted automatically. Default=600 seconds (10 minutes).
      用户session自动被删除的得默认时间是 600秒。

      sharedSession        boolean that says if this webapp should use the global shared session. Every webapp that has this on True will not use its own session, but instead share a single global session. This can be used for single signon, for instance, because the logged in user object is also shared. For more info see authorization. (The default value is False: use a unique, private session) Note: shared session does NOT mean that different users share a session. Every user ofcourse has her own private session!
      boolean值,它将告诉webapp是拥有公共的否共享session。一般每个webapp都打开此项,来代替单一的共享session。也可以使用单一标记,因为  logged in user对象也是共享的。更多信息见 authorization。(默认值是 False:使用唯一的,私有的session)注解:共享session并不是不同用户共享同一个session。每个用户当然有他们自己的私有 session。

      defaultOutputEncoding        Specify the output character encoding of dynamic pages (Ypages, snakelets) that don't specify an encoding themselves (or obtain one from a template page). If they set an encoding themselves, that one is used. Default=None; no encoding.
      指定动态页面的输出字符编码(Ypages,snakelets),如果页面自己没有指定字符编码,就会按此参数进行字符编码(或者从页面模版获得)。默认是 Default=None;没有编码。

      defaultContentType        Specify the content type of dynamic pages (Ypages, snakelets) that don't specify a content type themselves (or obtain one from a template page). If they set a content type themselves, that one is used.
      Default=text/html指定动态页面的内容类型,默认 text/html。

      defaultPageTemplate        Specify the default page template file to use for formatting dynamic pages without an explicit page template declaration. Default=None; no page template. Doesn't work on snakelets, only Ypages
      指定默认模版页面文件用于格式化动态页面,不通过直接模版声明。Default=None;默认没有页面模版。只在Ypage工作。

      defaultErrorPage        Specify the default errorpage to use for formatting server error pages. This saves you from having to specify an errorpage in every Ypage file. Works for snakelets and Ypages.
      指定默认错误页面文件来格式化server错误页面。避免您重复进行错误页面设置。在snakelets和Ypage都可以使用。

      indexPages        Setting this value allows you to use a custom 'index pages' list on a site-by-site basis. It will override the default list of index pages that Snakelets looks for. If you don't specify it, the default list is used. The built-in default list is index.y, index.html, index.htm (in this order). Only real files can be mentioned in this list. It is possible to use Snakelets as 'virtual' index pages but that is configured elsewhere.
      允许设置自定义的 ‘index 页面’列表。他将替代默认的index页面列表。如果你没有指定他,默认内置列表为 index.y . index.html . index.htm 。只有真实文件可以在列表中出现。您也可以使用虚拟页面,但这需要另外的配置。

      def dirListAllower(path): ...        define this function to allow directory listings for the path (regardless of user authorization). Return True if allowed. By default, directory listing is not allowed. Path is relative for the web app, for instance "img/picture.gif"
      通过定义此函数来实现对某些目录的列表访问(忽略用户授权)。如果可以访问返回True 。默认情况下目录列表不允许访问。使用相对路径,比如: ‘img/picture.gif’。

      def documentAllower(path): ...        define this function to allow serving the given document (regardless of user authorization). Return True if allowed. By default, all documents are allowed except Python source files (.py suffix). Path is relative for the web app, for instance "img/picture.gif"
      定义此函数来提供文档服务(忽略用户授权)。如果允许返回True。默认情况除了python源文件(.py后缀)以外所有文档都可以访问。采用相对路径。比如: ‘img/picture.gif’。

      authorizationPatterns        a dict that maps (relative) URL patterns to lists of privilege names that are allowed to access those URLs. Note that the full URL must match the pattern before authorization is required, so Snakelets automatically appends the *-wildcard to the end of your pattern to avoid security holes. (Also: the server-wide url prefix is automatically prepended to your patterns) See authorization. Default: all URLs are allowed (no privilege checks).
      允许访问特有名称列表的映射URL标记。注意 在授权请求之前完整URL必须匹配标记,Snakelets自动在您的标记后面添加*-wildcard来避免安全漏洞。(同样:server-wide url前缀将被预先自动添加到你的标记前)见 authorization 。默认:所有URL都是允许的(没有特权检测)。

      authenticationMethod        tuple (method, argument) that defines the user authentication method to use for the whole webapp. See authorization. Default: not specified. This setting can be overruled by a corresponding page declaration or snakelet method.
      为整个webapp定义用户验证。见 authorization 。 默认:无指定。这个设置可以被相应的页面或者snakelet 方法修改。

      def authorizeUser(method, url, user, passwd, request): ...        You must implement this method yourself if you let Snakelets do the user authentication. It must do the actual user/password checking, see authorization.
      如果您让Snakelets进行用户验证,您必须自己实现该方法。必须有 user/password 检测,见 authorization 。

      def init(webapp): ...        You may define this function to do your webapp's initialization. Parameter is the current webapp. Note: when you are deploying your webapp on multiple vhosts, the init is called once for each vhost! Be prepared for this, especially when you are doing system-global initialisation code such as registering server plugins... (you should trap possible errors, or add some code that makes sure that such things are only done once)
      您可能定义这个函数用来初始化您的webapp。参数值为当前的得webapp。 注意:如果您正在使用多重vhost 进行开发,init函数将在每一个vhost中被执行一次!请注意这一点,尤其是当您正在使用 system-global(系统全局)初始化代码的时候,比如注册系统插件…(您应该捕捉可能出现的错误,或者添加一些代码来确定这些注册操作只进行一次)。

      def close(webapp): ...        You may define this function to do your webapp's cleanup when it is removed. Parameter is the current webapp. Note: when you are deploying your webapp on multiple vhosts, the init is called once for each vhost!
      当您的webapp被移除的时候自动执行此函数。参数是当前的webapp。




vhost config: To make your web application appear on the server, you have to add it to the virtual host configuration file. See Starting the Server.
vhost 配置:如果想在server中运行您的webapp,您需要在虚拟主机中添加相应的配置文件。见Starting the Server。

Python module/package names: There is a big catch concerning the naming of your packages and modules in the web apps (for instance, the package where your snakelets are in, or the name(s) of the modules that contain your snakelets). They are not unique over all web applications (because every webapp's directory is placed in Python's module search path)! This means that you cannot have a module or package called "snakelets" in one webapp and also a module or package with that name in another web application. This also means that your code is not protected from (ab)use by another web application. This wil very likely not be fixed, so keep this in mind!
Python module/package 名称:您的 package 和 module 的名称在整个web应用程序中并不是唯一的(因为所有的webapp目录都在搜索路径范围之内)!这就意味着您不能有名为 “snakelets”的webapp,当然在其他web应用程序中的module或 package也不能用这个名字。也就是说使用同名的module/package您想要使用的module/package将不能保证在其他web应用程序中被运行。

Shared modules/libraries: place modules and packages that you want to easily share between webapps in the "userlibs" directory, as described in Starting and Configuring.
共享的 modules/libraries:将您想要共享的 module/packages 放到该目录下,Starting and Configuring中有比较详细的描述。

TOP

返回列表