Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/studio/static/doc/flask-docs/tutorial/dbinit.html
blob: 413914e73afb2794f450b1fd71ca3f4c111dbd01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Step 3: Creating The Database &mdash; Flask 0.8 documentation</title>
    
    <link rel="stylesheet" href="../_static/flasky.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '0.8',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="top" title="Flask 0.8 documentation" href="../index.html" />
    <link rel="up" title="Tutorial" href="index.html" />
    <link rel="next" title="Step 4: Request Database Connections" href="dbcon.html" />
    <link rel="prev" title="Step 2: Application Setup Code" href="setup.html" />
   
  
  <link rel="apple-touch-icon" href="../_static/touch-icon.png" />
  
  <link media="only screen and (max-device-width: 480px)" href="../_static/small_flask.css" type= "text/css" rel="stylesheet" />

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="dbcon.html" title="Step 4: Request Database Connections"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="setup.html" title="Step 2: Application Setup Code"
             accesskey="P">previous</a> |</li>
        <li><a href="../index.html">Flask 0.8 documentation</a> &raquo;</li>
          <li><a href="index.html" accesskey="U">Tutorial</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="step-3-creating-the-database">
<span id="tutorial-dbinit"></span><h1>Step 3: Creating The Database<a class="headerlink" href="#step-3-creating-the-database" title="Permalink to this headline">ΒΆ</a></h1>
<p>Flaskr is a database powered application as outlined earlier, and more
precisely, an application powered by a relational database system.  Such
systems need a schema that tells them how to store that information. So
before starting the server for the first time it&#8217;s important to create
that schema.</p>
<p>Such a schema can be created by piping the <cite>schema.sql</cite> file into the
<cite>sqlite3</cite> command as follows:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">sqlite3</span> <span class="o">/</span><span class="n">tmp</span><span class="o">/</span><span class="n">flaskr</span><span class="o">.</span><span class="n">db</span> <span class="o">&lt;</span> <span class="n">schema</span><span class="o">.</span><span class="n">sql</span>
</pre></div>
</div>
<p>The downside of this is that it requires the sqlite3 command to be
installed which is not necessarily the case on every system.  Also one has
to provide the path to the database there which leaves some place for
errors.  It&#8217;s a good idea to add a function that initializes the database
for you to the application.</p>
<p>If you want to do that, you first have to import the
<a class="reference external" href="http://docs.python.org/dev/library/contextlib.html#contextlib.closing" title="(in Python v3.3)"><tt class="xref py py-func docutils literal"><span class="pre">contextlib.closing()</span></tt></a> function from the contextlib package.  If you
want to use Python 2.5 it&#8217;s also necessary to enable the <cite>with</cite> statement
first (<cite>__future__</cite> imports must be the very first import):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">with_statement</span>
<span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">closing</span>
</pre></div>
</div>
<p>Next we can create a function called <cite>init_db</cite> that initializes the
database.  For this we can use the <cite>connect_db</cite> function we defined
earlier.  Just add that function below the <cite>connect_db</cite> function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">init_db</span><span class="p">():</span>
    <span class="k">with</span> <span class="n">closing</span><span class="p">(</span><span class="n">connect_db</span><span class="p">())</span> <span class="k">as</span> <span class="n">db</span><span class="p">:</span>
        <span class="k">with</span> <span class="n">app</span><span class="o">.</span><span class="n">open_resource</span><span class="p">(</span><span class="s">&#39;schema.sql&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
            <span class="n">db</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span><span class="o">.</span><span class="n">executescript</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
        <span class="n">db</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
</pre></div>
</div>
<p>The <a class="reference external" href="http://docs.python.org/dev/library/contextlib.html#contextlib.closing" title="(in Python v3.3)"><tt class="xref py py-func docutils literal"><span class="pre">closing()</span></tt></a> helper function allows us to keep a
connection open for the duration of the <cite>with</cite> block.  The
<a class="reference internal" href="../api.html#flask.Flask.open_resource" title="flask.Flask.open_resource"><tt class="xref py py-func docutils literal"><span class="pre">open_resource()</span></tt></a> method of the application object
supports that functionality out of the box, so it can be used in the
<cite>with</cite> block directly.  This function opens a file from the resource
location (your <cite>flaskr</cite> folder) and allows you to read from it.  We are
using this here to execute a script on the database connection.</p>
<p>When we connect to a database we get a connection object (here called
<cite>db</cite>) that can give us a cursor.  On that cursor there is a method to
execute a complete script.  Finally we only have to commit the changes.
SQLite 3 and other transactional databases will not commit unless you
explicitly tell it to.</p>
<p>Now it is possible to create a database by starting up a Python shell and
importing and calling that function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">flaskr</span> <span class="kn">import</span> <span class="n">init_db</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">init_db</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition-troubleshooting admonition ">
<p class="first admonition-title">Troubleshooting</p>
<p class="last">If you get an exception later that a table cannot be found check that
you did call the <cite>init_db</cite> function and that your table names are
correct (singular vs. plural for example).</p>
</div>
<p>Continue with <a class="reference internal" href="dbcon.html#tutorial-dbcon"><em>Step 4: Request Database Connections</em></a></p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper"><p class="logo"><a href="../index.html">
  <img class="logo" src="../_static/flask.png" alt="Logo"/>
</a></p><h3>Related Topics</h3>
<ul>
  <li><a href="../index.html">Documentation overview</a><ul>
  <li><a href="index.html">Tutorial</a><ul>
      <li>Previous: <a href="setup.html" title="previous chapter">Step 2: Application Setup Code</a></li>
      <li>Next: <a href="dbcon.html" title="next chapter">Step 4: Request Database Connections</a></li>
  </ul></li>
  </ul></li>
</ul>
  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../_sources/tutorial/dbinit.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="footer">
      &copy; Copyright 2010, Armin Ronacher.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a>.
    </div>
  </body>
</html>