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.

FIrst you have to create and configure your web application, and then you must fill it with web pages.

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).

The module's __init__.py must contain the configuration settings for your web app:

Attribute description
name The descriptive name for this 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.
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.
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.
configItems a dict that you can fill with any config items you want to be available in the web app trough the getConfigItem() method.
sessionTimeoutSecs the inactivity period it takes for a user session to be deleted automatically. Default=600 seconds (10 minutes).
sessionTimeoutPage the (webapp-relative) url for the page that will be shown when the user's session has become unavailable (usually due to a session timeout that caused the session to be destroyed in the server). Default behavior is to just try to create a new session - without notice.
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!
sharedSessionTLD Cookie domain to use for shared session cookies. Useful when the same webapp is mounted on mulitple virtual hosts (by aliasing only!), for example xx.domain.tld, yy.domain.tld, and you want to share sessions among these subdomains. Define sharedSessionTLD = 'domain.tld' and the shared session cookie is availble to both subdomains. Note: you have to do define this for all shared webapps. Also this cookie sharing does only work on aliased virtual hosts, not across real virtual hosts.
defaultRequestEncoding Specify the default encoding that will be used when reading incoming request data (such as form-posts). If you don't specify this, Python's default encoding is used (usually ASCII). You can override this in your page/snakelet by using request.setEncoding().
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. If you don't specify this, Python's default output encoding is used (usually ASCII) but beware that this will very likely break pages that try to use non-ASCII characters. If you want to be safe and support Unicode output, you should define a page output encoding, either by setting it globally using this option or by setting it on the pages itself.
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
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.
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.
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.
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"
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"
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).
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.
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.
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)
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!

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.

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!

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.

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/

The index page of the webapp will be shown if you type http://server.com/testapp/ or http://server.com/testapp in your browser. The trailing slash is not really required; you will be redirected to a correct url if it is missing. (except when there is a page in the root webapp with the same name, in this case the page is loaded and you will not be redirected).

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.

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.

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.

The server uses the following order to determine what is returned for a requested 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.

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.

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.

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 suffixes and authorization patterns: when checking authorization patterns, Snakelets takes smart suffixes into account. For more info see 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.

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.

Page Creation Tutorial

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

Snakelets manual - Back to index