Skip to content
Myr

Proofreading the documentation

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Chris Edgemon · committed by Chris Edgemon · parent 4ff9493 · Browse files · 8 files+58 added−58 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+58 added−58 removed

  • other:+58 added−58 removed

8 files+58 added−58 removed

modified:docs/deploying/mod_wsgi.rst+3 added-3 removed
9 unmodified lines
1011If you don't have `mod_wsgi` installed yet you have to either install it using12a package manager or compile it yourself.1314The mod_wsgi `installation instructions`_ cover installation instructions for15source installations on UNIX systems.14The mod_wsgi `installation instructions`_ cover source installations on UNIX 15systems.1617If you are using ubuntu / debian you can apt-get it and activate it as follows::1819 # apt-get install libapache2-mod-wsgi
23 unmodified lines
4344If you don't have a factory function for application creation but a singleton45instance you can directly import that one as `application`.4647Store that file somewhere where you will find it again (eg:47Store that file somewhere that you will find it again (e.g.:48`/var/www/yourapplication`) and make sure that `yourapplication` and all49the libraries that are in use are on the python load path. If you don't50want to install it system wide consider using a `virtual python`_ instance.51
29 unmodified lines
modified:docs/patterns/packages.rst+3 added-3 removed
46 unmodified lines
47What did we gain from this? Now we can restructure the application a bit48into multiple modules. The only thing you have to remember is the49following quick checklist:50511. the `Flask` application object creation have to be in the511. the `Flask` application object creation has to be in the52 `__init__.py` file. That way each module can import it safely and the53 `__name__` variable will resole to the correct package.53 `__name__` variable will resolve to the correct package.542. all the view functions (the ones with a :meth:`~flask.Flask.route`55 decorator on top) have to be imported when in the `__init__.py` file.56 Not the objects itself, but the module it is in. Do the importing at56 Not the object itself, but the module it is in. Do the importing at57 the *bottom* of the file.5859Here an example `__init__.py`::60
27 unmodified lines
modified:docs/patterns/sqlalchemy.rst+9 added-9 removed
4 unmodified lines
56Many people prefer `SQLAlchemy`_ for database access. In this case it's7encouraged to use a package instead of a module for your flask application8and drop the models into a separate module (:ref:`larger-applications`).9Although that is not necessary but makes a lot of sense.9While that is not necessary, it makes a lot of sense.1011There are three very common ways to use SQLAlchemy. I will outline each12of them here:13
37 unmodified lines
51 def shutdown_session(response):52 db_session.remove()53 return response5455Here an example model (put that into `models.py` for instance)::55Here is an example model (put this into `models.py`, e.g.)::5657 from sqlalchemy import Column, Integer, String58 from yourapplication.database import Base59
9 unmodified lines
6970 def __repr__(self):71 return '<User %r>' % (self.name, self.email)7273You can insert entries into the database like this then:73You can insert entries into the database like this:7475>>> from yourapplication.database import db_session76>>> from yourapplication.models import User77>>> u = User('admin', 'admin@localhost')
16 unmodified lines
9495Manual object relational mapping has a few upsides and a few downsides96versus the declarative approach from above. The main difference is that97you define tables and classes separately and map them together. It's more98flexible but a little more to type. In general it works similar to the98flexible but a little more to type. In general it works like the99declarative approach, so make sure to also split up your application into100multiple modules in a package.101102Here the example `database.py` module for your application::102Here is an example `database.py` module for your application::103104 from sqlalchemy import create_engine, MetaData105 from sqlalchemy.orm import scoped_session, sessionmaker106
4 unmodified lines
111 bind=engine)) 112 def init_db():113 metadata.create_all(bind=engine)114115As for the declarative approach you need to close down the session after115As for the declarative approach you need to close the session after116each request. Put this into your application module::117118 from yourapplication.database import db_session119
1 unmodified line
121 def shutdown_session(response):122 db_session.remove()123 return response124125Here an example table and model (put that into `models.py` for instance)::125Here is an example table and model (put this into `models.py`)::126127 from sqlalchemy import Table, Column, Integer, String128 from sqlalchemy.orm import mapper129 from yourapplication.database import metadata, db_session
41 unmodified lines
171>>> con.execute(users.insert(name='admin', email='admin@localhost'))172173SQLAlchemy will automatically commit for us.174175To query your database, yu use the engine directly or use a connection:175To query your database, you use the engine directly or use a connection:176177>>> users.select(users.c.id == 1).execute().first()178(1, u'admin', u'admin@localhost')179
2 unmodified lines
182>>> r = users.select(users.c.id == 1).execute().first()183>>> r['name']184u'admin'185186You can also pass string of SQL statements to the186You can also pass strings of SQL statements to the187:meth:`~sqlalchemy.engine.base.Connection.execute` method:188189>>> engine.execute('select * from users where id = :1', [1]).first()190(1, u'admin', u'admin@localhost')
3 unmodified lines
modified:docs/patterns/sqlite3.rst+3 added-3 removed
1 unmodified line
23Using SQLite 3 with Flask4=========================56In Flask you can implement opening of dabase connections at the beginning6In Flask you can implement opening of database connections at the beginning7of the request and closing at the end with the8:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`9decorators in combination with the special :class:`~flask.g` object.1011So here a simple example how you can use SQLite 3 with Flask::11So here a simple example of how you can use SQLite 3 with Flask::1213 import sqlite314 from flask import g15
53 unmodified lines
69---------------7071Relational databases need schemas, so applications often ship a72`schema.sql` file that creates the database. It's a good idea to provide73a function that creates the database bases on that schema. This function73a function that creates the database based on that schema. This function74can do that for you::7576 from contextlib import closing77
10 unmodified lines
modified:docs/becomingbig.rst+9 added-9 removed
6 unmodified lines
7designed for large scale applications and does not attempt to do so, but8that does not mean you picked the wrong tool in the first place.910Flask is powered by Werkzeug and Jinja2, two libraries that are in use at11a number of large websites out there and all Flask does is bringing those11a number of large websites out there and all Flask does is bring those12two together. Being a microframework, Flask is literally a single file.13What that means for large applications is that it's probably a good idea14to take the code from Flask and put it into a new module within the15applications and expanding on that.15applications and expand on that.1617What Could Be Improved?18-----------------------1920For instance it makes a lot of sense to change the way endpoints (the21names of the functions / URL rules) are handled to also take the module22name into account. Right now the function name is the URL name, but23imagine you have a large applications consisting of multiple components.23imagine you have a large application consisting of multiple components.24In that case, it makes a lot of sense to use dotted names for the URL25endpoints.2627Here some suggestions how Flask can be modified to better accomodate large28scale applications:27Here are some suggestions for how Flask can be modified to better 28accomodate large-scale applications:2930- implement dotted names for URL endpoints31- get rid of the decorator function registering which causes a lot32 of troubles for applications that have circular dependencies. It
1 unmodified line
34 initializes or certain URLs will not be available right away. A35 better solution would be to have one module with all URLs in there and36 specifing the target functions explicitly or by name and importing37 them when needed.38- switch to explicit request object passing. This makes it more to type38- switch to explicit request object passing. This requires more typing39 (because you now have something to pass around) but it makes it a40 whole lot easier to debug hairy situations and to test the code.41- integrate the `Babel`_ i18n package or `SQLAlchemy`_ directly into the42 core framework.4344.. _Babel: http://babel.edgewall.org/45.. _SQLAlchemy: http://www.sqlalchemy.org/4647Why does not Flask do all that by Default?47Why does Flask not do all that by Default?48------------------------------------------4950There is a huge difference between a small application that only has to51handle a couple of requests per second and with an overall code complexity52of less than 4000 lines of code or something of larger scale. At one52of less than 4000 lines of code and something of larger scale. At some53point it becomes important to integrate external systems, different54storage backends and more.5556If Flask was designed with all these contingencies in mind, it would be a57much more complex framework and less easy to get started with.57much more complex framework and harder to get started with.
modified:docs/design.rst+11 added-11 removed
1Design Decisions in Flask2=========================34If you are curious why Flask does certain things the way it does and not5different, this section is for you. This should give you an idea about5differently, this section is for you. This should give you an idea about6some of the design decisions that may appear arbitrary and surprising at7first, especially in direct comparison with other frameworks.89
33 unmodified lines
43something it can be very helpful to create a minimal application to test44specific behavior. When the application object is deleted everything it45allocated will be freed again.4647Another thing that becomes possible with having an explicit object laying47Another thing that becomes possible when you have an explicit object laying48around in your code is that you can subclass the base class49(:class:`~flask.Flask`) to alter specific behaviour. This would not be50possible without hacks if the object was created ahead of time for you50possible without hacks if the object were created ahead of time for you51based on a class that is not exposed to you.5253But there is another very important reason why Flask depends on an54explicit instanciation of that class: the package name. Whenever you
27 unmodified lines
82that limitation that Jinja2 is *always* configured will probably go away,83the decision to bundle one template engine and use that will not.8485Template engines are like programming languages and each of those engines86has a certain understandment about how things work. On the surface they86has a certain understanding about how things work. On the surface they87all work the same: you tell the engine to evaluate a template with a set88of variables and take the return value as string.8990But that's about where similarities end. Jinja2 for example has an91extensive filter system, a certain way to do template inheritance, support92for reusable blocks (macros) that can be used from inside templates and93also from Python code, is using unicode for all operations, supports93also from Python code, uses unicode for all operations, supports94iterative template rendering, configurable syntax and more. On the other95hand an engine like Genshi is based on XML stream evaluation, template96inheritance by taking the availability of XPath into account and more.97Mako on the other hand treats templates similar to Python modules.9899When it comes to bridge a template engine with an application or framework100there is more than just rendering templates. Flask uses Jinja2's101extensive autoescaping support for instance. Also it provides ways to102access macros from Jinja2 templates.99When it comes to connecting a template engine with an application or 100framework there is more than just rendering templates. For instance,101Flask uses Jinja2's extensive autoescaping support. Also it provides 102ways to access macros from Jinja2 templates.103104A template abstraction layer that would not take the unique features of105the template engines away is a science on its own and a too large106undertaking for a microframework like Flask.
7 unmodified lines
114over to the Ruby side of web development there we have a protocol very115similar to WSGI. Just that it's called Rack there, but besides that it116looks very much like a WSGI rendition for Ruby. But nearly all117applications in Ruby land do not work with Rack directly, but on top of a118lirbary with the same name. This Rack library has two equivalents in118library with the same name. This Rack library has two equivalents in119Python: WebOb (formerly Paste) and Werkzeug. Paste is still around but120from my understanding it's sortof deprecated in favour of WebOb. The120from my understanding it's sort of deprecated in favour of WebOb. The121development of WebOb and Werkzeug started side by side with similar ideas122in mind: be a good implementation of WSGI for other applications to take123advantage.124
23 unmodified lines
modified:docs/installation.rst+9 added-9 removed
7 unmodified lines
8way and why there are multiple ways.910Flask depends on two external libraries: `Werkzeug11<http://werkzeug.pocoo.org/>`_ and `Jinja2 <http://jinja.pocoo.org/2/>`_.12The first on is responsible for interfacing WSGI the latter to render12The first one is responsible for interfacing WSGI the latter for rendering13templates. Now you are maybe asking, what is WSGI? WSGI is a standard14in Python that is basically responsible for ensuring that your application15is behaving in a specific way that you can run it on different15is behaving in a specific way so that you can run it on different16environments (for example on a local development server, on an Apache2, on17lighttpd, on Google's App Engine or whatever you have in mind).1819So how do you get all that on your computer in no time? The most kick-ass
5 unmodified lines
25Virtualenv is what you want to use during development and in production if26you have shell access. So first: what does virtualenv do? If you are27like me and you like Python, chances are you want to use it for another28project as well. Now the more projects you have, the more likely it is29that you will be working with different versions of Python itself or a30library involved. Because let's face it: quite often libraries break31backwards compatibility and it's unlikely that your application will32not have any dependencies, that just won't happen. So virtualenv for the29that you will be working with different versions of Python itself or at30least an individual library. Because let's face it: quite often libraries 31break backwards compatibility and it's unlikely that your application will32not have any dependencies, that just won't happen. So virtualenv to the33rescue!3435It basically makes it possible to have multiple side-by-side36"installations" of Python, each for your own project. It's not actually
9 unmodified lines
46or even better::4748 $ sudo pip install virtualenv4950Changes are you have virtualenv installed on your system then. Maybe it's50Chances are you have virtualenv installed on your system then. Maybe it's51even in your package manager (on ubuntu try ``sudo apt-get install52python-virtualenv``).5354If you are on Windows and missing the `easy_install` command you have to
96 unmodified lines
151Once you have done that it's important to add the `easy_install` command152and other Python scripts to the path. To do that you have to add the153Python installation's Script folder to the `PATH` variable.154155To do that, click right on your "Computer" desktop icon and click155To do that, right-click on your "Computer" desktop icon and click156"Properties". On Windows Vista and Windows 7 then click on "Advanced System157settings", on Windows XP click on the "Advanced" tab instead. Then click158on the "Environment variables" button and double click on the "Path"159variable in the "System variables" section.
4 unmodified lines
164the following value::165166 ;C:\Python26\Scripts167168Then you are done. To check if it worked, open the cmd and execute168Then you are done. To check that it worked, open the cmd and execute169"easy_install". If you have UAC enabled it should prompt you for admin170privileges.171172
1 unmodified line
modified:docs/testing.rst+11 added-11 removed
6 unmodified lines
78Not sure where that is coming from, and it's not entirely correct, but9also not that far from the truth. Untested applications make it hard to10improve existing code and developers of untested applications tend to11become pretty paranoid. If an application however has automated tests you12can savely change things and you will instantly know if your change broke11become pretty paranoid. If an application however has automated tests, you12can safely change things and you will instantly know if your change broke13something.1415Flask gives you a couple of ways to test applications. It mainly does16that by exposing the Werkzeug test :class:`~werkzeug.Client` class to your17code and handling the context locals for you. You can then use that with18your favourite testing solution. In this documentation we will us the18your favourite testing solution. In this documentation we will use the19:mod:`unittest` package that comes preinstalled with each Python20installation.2122The Application
26 unmodified lines
4950 if __name__ == '__main__':51 unittest.main()5253The code in the `setUp` function creates a new test client and initialize53The code in the `setUp` function creates a new test client and initializes54a new database. That function is called before each individual test function.55What the test client does for us is giving us a simple interface to the55What the test client does is give us a simple interface to the56application. We can trigger test requests to the application and the57client will also keep track of cookies for us.5859Because SQLite3 is filesystem based we can easily use the tempfile module59Because SQLite3 is filesystem-based we can easily use the tempfile module60to create a temporary database and initialize it. Just make sure that you61keep a reference to the :class:`~tempfile.NamedTemporaryFile` around (we62store it as `self.db` because of that) so that the garbage collector does63not remove that object and with it the database from the filesystem.
47 unmodified lines
111 Ran 1 test in 0.034s112113 OK114115Of course you can submit forms with the test client as well which we will115Of course you can submit forms with the test client as well, which we will116use now to log our user in.117118Logging In and Out119------------------120121The majority of the functionality of our application is only available for122the administration user. So we need a way to log our test client into the122the administration user. So we need a way to log our test client in to the123application and out of it again. For that we fire some requests to the124login and logout pages with the required form data (username and125password). Because the login and logout pages redirect, we tell the126client to `follow_redirects`.127128Add the following two methods do your `FlaskrTestCase` class::128Add the following two methods to your `FlaskrTestCase` class::129130 def login(self, username, password):131 return self.app.post('/login', data=dict(132 username=username,
3 unmodified lines
136 def logout(self):137 return self.app.get('/logout', follow_redirects=True)138139Now we can easily test if logging in and out works and that it fails with140invalid credentials. Add this as new test to the class::140invalid credentials. Add this new test to the class::141142 def test_login_logout(self):143 rv = self.login(flaskr.USERNAME, flaskr.PASSWORD)144 assert 'You were logged in' in rv.data
19 unmodified lines
164 assert 'No entries here so far' not in rv.data165 assert '&lt;Hello&gt' in rv.data166 assert '<strong>HTML</strong> allowed here' in rv.data167168Here we also check that HTML is allowed in the text but not in the title168Here we check that HTML is allowed in the text but not in the title,169which is the intended behavior.170171Running that should now give us three passing tests::172
14 unmodified lines