The nohup commands makes sure the server does not die when you close the shell. On Ubuntu, or other Debian-based Linux distribution, edit "web2py. On Fedora, or any other distributions based on Fedora, edit "web2py. Nginx is a free, open-source web server that has rapidly been gaining popularity for its amazing performance.
Unlike traditional servers, Nginx does not use threads. This architecture results in a small and predictable memory usage, even under heavy load. Nginx is easy to configure and its configuration files and simpler and more compact than the corresponding Apache ones. Lighttpd FastCGI fcgihandler. You can install Lighttpd on a Ubuntu or other Debian-based Linux distribution with the following shell command:. In the config file, write something like:.
As in the case of Apache, it is possible to setup Lighttpd to deal with static files directly, and to force some applications over HTTPS. Refer to the Lighttpd documentation for details. The administrative interface must be disabled when web2py runs on a shared host with FastCGI, or it will be exposed to the other users. There are times, specifically on shared hosts, when one does not have the permission to configure the Apache config files directly. Its web interface is written in Python.
In addition, there is no restart required for most of the changes. Download Cherokee [ cherokee ]. This will start web2py under FastCGI handler. By default, cherokee-admin only listens at local interface on port This is not a problem if you have full, physical access on that machine. If this is not the case, you can force it to bind to an IP address and port by using the following options:.
In cherokee-admin web interface, click "info sources". Choose "Local Interpreter". Write in the following code, then click "Add New". PostgreSQL is a free and open source database which is used in demanding production environments, for example, to store the.
It has very fast and solid transaction support, and provides an auto-vacuum feature that frees the administrator from most database maintenance tasks. It is wise to run the web server s and the database server on different machines. In this case, the machines running the web servers should be connected with a secure internal physical network, or should establish SSL tunnels to securely connect with the database server. When restarting the PostgreSQL server, it should notify which port it is running on.
Unless you have multiple database servers, it should be Once the database server is up and running, create a user and a database so that web2py applications can use it:. The first of the commands will grant superuser-access to the new user, called myuser.
It will prompt you for a password. Normally you use one database for each application, and multiple instances of the same application connect to the same database. It is also possible for different applications to share the same database.
Task definition is done in a model file. But the initial queuing of a repeating task is most easily done from a non-exposed controller function. By doing this in a controller rather than in a model file, you remove unnecessary database accesses that would occur on every request to your website. A non-exposed function is any controller function that has an argument, so writing something like the following in a controller e.
Your application may have a need for a pre-populated database table. A simple example might be a table of color names, or the names of the months perhaps in a special format not used in Python datetime routines. More complicated examples might include an initial inventory of parts, or the initial pages of a wiki.
The simple examples might be done via db. As in the task queuing section above, this should be done using non-exposed controller functions. Table definition for a database is done in model files, but model files are read on every request, so one-time actions should not be in the model files where they would lower the responsiveness of your site.
Again, a non-exposed function is any controller function that has an argument, so writing something like the following in a controller e. See also Chapter 14, Populating database with dummy. If you don't need to run Apache for some other application on the server, on modern Windows Servers installing web2py behind IIS is easier and more performant. We'll start from the assumption that you're running R2. The terms used for R2 are slightly different but it shouldn't be a problem to reconcile the instructions.
Of course the requirements are a Python installed on the server and you being able to run web2py with something like. This means that nothing is broken in your installation and that you can host successfully web2py behind IIS. In order to serve static files with IIS, we need also the Url Rewrite module that you can install from here.
To let IIS "speak" with python, we need to install the wfastcgi module from here. This will install a little script, wfasctgi. We need to create a FastCGI process that will be mapped to the handler running web2py. From 2. Now, copy the web. This is sufficient to use web2py as the "root" application of a site. However, it is quite similar to Linux, so please read the Linux Apache notes above. Here we assume a Windows binary Python 2. Modern apache Windows binaries e. Instead, you download them from partner sites, such as ApacheHaus.
The Apache site has a full list of such partners; search for Apache 2. However, the Windows binary may not come with the wsgi module. After you install Apache, put the. You'll need to modify httpd. The Windows binary is most likely configured to load and configure the SSL modules 'out of the box' the Apache Haus binary is like this. Typically this means port 80 and port although your Windows server may be using these ports because IIS may be installed, in which case choose alternate ports. Now you can right-click on the red feather-like taskbar icon to "Open Apache Monitor" and then start, stop and restart Apache as required.
What Linux calls a daemon, Windows calls a service. The same is true of the web2py scheduler. Rather than maintaining Windows service code in web2py. It also means a consistent way of running web2py services, scheduler services and clean-up processes like session deletes. The use of the previous -W command-line option is no longer supported.
The nssm method does not use the options. Instead, options are passed on the command line some exmaples are provided below. Running the scheduler as a Windows service makes a lot of sense. It wraps around an executable command to turn it into a service. The command to start the scheduler is pythonw. Before doing this, you need to choose a name for your service. This means that they need to register or be registered and log in. Auth provides multiple login methods.
To start using Auth , you need at least this code in a model file, which is also provided with the web2py "welcome" application and assumes a db connection object:. By default, web2py uses email for login.
If instead you want to log in using username set auth. This is actually provided by web2py's standard CSRF protection whenever forms are generated in a session. However, under some circumstances, the overhead of creating a session for login,password request and reset attempts may be undesirable.
DOS attacks are theoretically possible. CSRF protection can be disabled for Auth forms as of v 2. Note that doing this purely to avoid session overload on a busy site is not recommended because of the introduced security risk. Instead, see the Deployment chapter for advice on reducing session overheads. The password field of the db. This is no longer necessary for new applications since passwords are salted with an individual random salt.
If multiple apps share the same auth database you may want to disable migrations: auth. To expose Auth , you also need the following function in a controller for example in "default.
The auth object and the user action are already defined in the scaffolding application. Notice that this function simply displays a form and therefore it can be customized using normal custom form syntax. By default they are all exposed, but it is possible to restrict access to only some of these actions. To restrict access to functions to only logged in visitors, decorate the function as in the following example. Any function can be decorated, not just exposed actions.
Of course this is still only a very simple example of access control. More complex examples will be discussed later. There is also a auth. Similarly, auth. The auth. It can be set to a string where to redirect the user if registration files or to a callable object. It is called if registration fails.
If you want to allow visitors to register but not to log in until registration has been approved by the administrator:. You can approve a registration via the appadmin interface. A registration is approved when this field is set to blank.
Via the appadmin interface, you can also block a user from logging in. Notice that this will prevent a visitor from logging in but it will not force a visitor who is already logged in to log out.
The word "disabled" may be used instead of "blocked" if preferred, with exactly the same behavior. If you want to allow people to register and automatically log them in after registration but still want to send an email for verification so that they cannot login again after logout, unless they completed the instructions in the email, you can accomplish it as follows:.
Dropbox is discussed as a special case in Chapter 14 since it allows more than just login, it also provides storage services for the logged in users. Janrain Engage is a service that provides middleware authentication. You can register with Janrain. Now edit the model of your web2py application and place the following lines somewhere after the definition of the auth object :. The first line imports the new login method, the second line disables local registration, and the third line asks web2py to use the RPX login method.
To obtain then login at janrain. When a new user logins for the first time, web2py creates a new db. Which fields are provided depends on the login method selected by the user. You can customize the mapping between the data provided by Janrain and the data stored in db. Here is an example for Facebook:.
The keys in the dictionary are fields in db. Look at the online Janrain documentation for details on the latter. This login form is fully integrated with web2py Role Based Access Control and you can still create groups, make users members of groups, assign permissions, block users, etc. Janrain's free Basic service allows up to unique registered users to sign in annually. Accommodating more users requires an upgrade to one of their paid service tiers.
The API to do so is described later in the chapter. It's experimental because it may be replaced with automatic detection of when ajax is required. Another way to do this, although not really recommended, consists of defining your auth tables yourself. If a table is declared before auth. Here is how to do it:. You can add any field you wish, and you can change validators but you cannot remove the fields marked as "required" in this example.
If you add a field called "username", it will be used in place of "email" for login. If you do, you will need to add a validator as well:. Note that Auth caches the logged in user in the session and that's what you get in auth. The names of the table can be changed by reassigning the above variables after the auth object is defined and before the Auth tables are defined. For example:. Note: auth. To avoid this do:. In that case, auth. Auth provides multiple login methods and hooks to create new login methods.
Now the action returns a dictionary defining a message. When an action returns a dictionary, web2py looks for a view with the name. Here [extension] is the requested extension. If no extension is specified, it defaults to "html", and that is what we will assume here. Notice that message here is not a web2py keyword but is defined in the action. So far we have not used any web2py keywords.
If web2py does not find the requested view, it uses the "generic. These generic views can be modified for each application individually, and additional views can be added easily. Generic views are a development tool. In production every action should have its own view. In fact, by default, generic views are only enabled from localhost. Let's now add a counter to this page that will count how many times the same visitor displays the page.
The session is a container for variables that are stored server-side. The unique id is sent to the browser via a cookie. When the visitor requests another page from the same application, the browser sends the cookie back, it is retrieved by web2py, and the corresponding session is restored. Notice that counter is not a web2py keyword but session is. We are asking web2py to check whether there is a counter variable in the session and, if not, to create one and set it to 1.
If the counter is there, we ask web2py to increase the counter by 1. Finally we pass the value of the counter to the view.
The counter is associated with each visitor, and is incremented each time the visitor reloads the page. Different visitors see different counters. Now create two pages first and second , where the first page creates a form, asks the visitor's name, and redirects to the second page, which greets the visitor by name. In both views we have extended the basic "layout. The layout view keeps the look and feel of the two pages consistent. The layout file can be edited and replaced easily, since it mainly contains HTML code.
The mechanism for form submission that we used before is very common, but it is not good programming practice. All input should be validated and, in the above example, the burden of validation would fall on the second action. Thus the action that performs the validation is different from the action that generated the form. This tends to cause redundancy in the code. A better pattern for form submission is to submit forms to the same action that generated them, in our example the "first".
The "first" action should receive the variables, process them, store them server-side, and redirect the visitor to the "second" page, which retrieves the variables. This mechanism is called a postback.
From the point of view of the visitor, the self-submission behaves exactly the same as the previous implementation. We have not added validation yet, but it is now clear that validation should be performed by the first action.
This approach is better also because the name of the visitor stays in the session, and can be accessed by all actions and views in the application without having to be passed around explicitly. Note that if the "second" action is ever called before a visitor name is set, it will display "Hello anonymous" because session. Alternatively we could have added the following code in the controller inside the second function :. This is an ad hoc mechanism that you can use to enforce authorization on controllers, though see Chapter 9 for a more powerful method.
With web2py we can move one step further and ask web2py to generate the form for us, including validation. They can be used to build forms either in the controller or in the view. The attributes of the input tags are specified by the named arguments starting with underscore. The form. If the self-submitted form passes validation, it stores the variables in the session and redirects as before.
If the form does not pass validation, error messages are inserted into the form and shown to the user, as below:. In all our examples we have used the session to pass the user name from the first action to the second. We could have used a different mechanism and passed data as part of a redirect URL:.
Mind that in general it is not a good idea to pass data from one action to another using the URL. It makes it harder to secure the application.
It is safer to store the data in a session. Your code is likely to include hardcoded strings such as "What is your name? You should be able to customize strings without editing the code and in particular insert translations for these strings in different languages.
In this way if a visitor has the language preference of the browser set to "Italian", web2py will use the Italian translation for the strings, if available. This feature of web2py is called "internationalization" and it is described in more detail in the next chapter. Here we just observe that in order to use this feature you should markup strings that needs translation.
This is done by wrapping a quoted string in code such as. It is good practice to do this for every string in the code field labels, flash messages, etc. Once the strings are identified and marked up, web2py takes care of almost everything else. The admin interface also provides a page where you can translate each string in the languages you desire to support.
It is integrated with both the internationalization engine and the markmin renderer. Here, as another example, we wish to create a web application that allows the administrator to post images and give them a name, and allows the visitors of the web site to view the named images and submit comments posts.
As before, from the site page in admin , create a new application called images , and navigate to the edit page:. We start by creating a model, a representation of the persistent data in the application the images to upload, their names, and the comments.
We assume the code below will replace any existing code in "db. Models and controllers must have a. If the extension is not provided, it is appended by web2py. Views instead have a. Line 1 defines a global variable called db that represents the database connection. When using SQLite, if the database file does not exist, it is created. You can change the name of the file, as well as the name of the global variable db , but it is convenient to give them the same name, to make it easy to remember.
Lines define a table "image". The first argument, "image", is the name of the table we are defining. The other arguments are the fields belonging to that table. This table has a field called "title", a field called "file", and a field called "id" that serves as the table primary key "id" is not explicitly declared because all tables have an id field by default.
The field "title" is a string, and the field "file" is of type "upload". This behavior is called "migration". Line 6 defines a format string for the table. It determines how a record should be represented as a string. Notice that the format argument can also be a function that takes a record and returns a string.
For example:. Lines define another table called "post". In line 14, db. Here we require that the "title" is unique:. The objects representing these constraints are called validators. Multiple validators can be grouped in a list. Validators are executed in the order they appear. As far as the database is concerned, we had already declared this when we defined the table "post".
Now we are explicitly telling the model that this condition should be enforced by web2py, too, at the form processing level when a new comment is posted, so that invalid values do not propagate from input forms to the database.
Once a model is defined, if there are no errors, web2py creates an application administration interface to manage the database. You access it via the "database administration" link in the edit page or directly:.
This interface is coded in the controller called "appadmin. From now on, we will refer to this interface simply as appadmin. It allows the administrator to insert new database records, edit and delete existing records, browse tables, and perform database joins. The first time appadmin is accessed, the model is executed and the tables are created. You can see the generated SQL from the edit page by clicking on the "sql.
Notice that the link is not present until the tables have been created. If you were to edit the model and access appadmin again, web2py would generate SQL to alter the existing tables. The generated SQL is logged into "sql. When the form is submitted and an image file is uploaded, the file is renamed in a secure way that preserves the extension, it is saved with the new name under the application "uploads" folder, and the new name is stored in the db.
This process is designed to prevent directory traversal attacks. At the bottom we find the interpreter. Moving up we find the web server rocket , the libraries, and the applications. Each application consists for its own MVC design models, controllers, views, modules, languages, databases, and static files.
Each application includes its own database administration code appadmin. Every web2py instance ships with three applications: welcome the scaffolding app , admin the web based IDE , and examples copy of website and examples. When web2py was born, there was only Python version 2. It took almost 10 years, but in web2py was finally made compatible with both Python 2.
The older Python 2. Pyhon 3 compatibility was indeed a huge milestone for many and many reasons but it required a careful check and rewrite of most of the framework. And the need of compatibility of all the required external libraries was a missing requirement for a long time. For new projects, we suggest you to use the latest release of web2py in the source form and to run it with Pyton 3.
For existing projects, you should instead evaluate carefully what to do: remaining with Python 2 or begining the conversion of your application to Python 3. Be careful: web2py apps created with Python 2 require web2py running under Python 2 and apps created using Python 3 requires web2py running Python 3. They cannot be mixed. This book only covers basic web2py functionalities and the API that ships with web2py.
This book does not cover web2py appliances i. You can download web2py appliances from the corresponding web site [ appliances ]. You can find additional topics discussed on the usergroup [ usergroup ]. The main support channel is the usergroup [ usergroup ] , with dozens of posts every day. Even if you're a newbie, don't hesitate to ask - we'll be pleased to help you. Last but not least, you can have professional support see the web site for details.
Any help is really appreciated. For more information on contributing, please see Chapter PEP8 [ style ] contains good style practices when programming with Python. You will find that web2py does not always follow these rules. This is not because of omissions or negligence; it is our belief that the users of web2py should follow these rules and we encourage it.
0コメント