Debian Codegraph @

docs/getting-started.rst

raw
1 .. _getting-started:
2
3 Getting Started
4 ===============
5
6 The goal of this document is to help get you up and running quickly. So without
7 further ado, let's get started.
8
9 .. note::
10 Hopefully you have some familiarity with the `flask framework <https://flask.palletsprojects.com/>`_ and
11 the `peewee orm <https://docs.peewee-orm.com/>`_, but if not those links
12 should help you get started.
13
14 .. note::
15 For a complete example project, check the `example app <https://github.com/coleifer/flask-peewee/tree/master/example>`_
16 that ships with flask-peewee.
17
18
19 Creating a flask app
20 --------------------
21
22 First, be sure you have :ref:`installed flask-peewee and its dependencies <installation>`.
23 You can verify by running the test suite: ``python runtests.py``.
24
25 After ensuring things are installed, open a new file called "app.py" and enter the
26 following code:
27
28 .. code-block:: python
29
30 from flask import Flask
31
32 app = Flask(__name__)
33 app.config.from_object(__name__)
34
35 if __name__ == '__main__':
36 app.run()
37
38 This isn't very exciting, but we can check out our project by running the app:
39
40 .. code-block:: console
41
42 $ python app.py
43 * Serving Flask app 'app'
44 * Debug mode: off
45 * Running on http://127.0.0.1:5000/
46 Press CTRL+C to quit
47
48 Navigating to the url listed will show a simple 404 page, because we haven't
49 configured any templates or views yet.
50
51 Creating a simple model
52 -----------------------
53
54 Let's add a simple model. Before we can do that, though, it is necessary to
55 initialize the peewee database wrapper and configure the database:
56
57 .. code-block:: python
58
59 from flask import Flask
60
61 # flask-peewee bindings
62 from flask_peewee.db import Database
63
64 # configure our database
65 DATABASE = {
66 'name': 'example.db',
67 'engine': 'peewee.SqliteDatabase',
68 }
69 DEBUG = True
70 SECRET_KEY = 'ssshhhh'
71
72 app = Flask(__name__)
73 app.config.from_object(__name__)
74
75 # instantiate the db wrapper
76 db = Database(app)
77
78 if __name__ == '__main__':
79 app.run()
80
81
82 What this does is provides us with request handlers which connect to the database
83 on each request and close it when the request is finished. It also provides a
84 base model class which is configured to work with the database specified in the
85 configuration.
86
87 Now we can create a model:
88
89 .. code-block:: python
90
91 import datetime
92 from peewee import *
93
94
95 class Note(db.Model):
96 message = TextField()
97 created = DateTimeField(default=datetime.datetime.now)
98
99
100 .. note::
101 The model we created, ``Note``, subclasses ``db.Model``, which in turn is
102 a subclass of ``peewee.Model`` that is pre-configured to talk to our database.
103
104
105 Setting up a simple base template
106 ---------------------------------
107
108 We'll need a simple template to serve as the base template for our app, so create
109 a folder named ``templates``. In the ``templates`` folder create a file ``base.html``
110 and add the following:
111
112 .. code-block:: html
113
114 <!doctype html>
115 <html>
116 <title>Test site</title>
117 <body>
118 <h2>{% block content_title %}{% endblock %}</h2>
119 {% block content %}{% endblock %}
120 </body>
121 </html>
122
123
124 Adding users to the site
125 ------------------------
126
127 Before we can edit these ``Note`` models in the admin, we'll need to have some
128 way of authenticating users on the site. This is where :py:class:`Auth` comes in.
129 :py:class:`Auth` provides a ``User`` model and views for logging in and logging out,
130 among other things, and is required by the :py:class:`Admin`.
131
132 .. code-block:: python
133
134 from flask_peewee.auth import Auth
135
136 # create an Auth object for use with our flask app and database wrapper
137 auth = Auth(app, db)
138
139 Let's also modify the code that runs our app to ensure our tables get created
140 if need be:
141
142 .. code-block:: python
143
144 if __name__ == '__main__':
145 # Use the underlying Peewee database to create tables at startup
146 # if they do not exist.
147 with db.database:
148 db.database.create_tables([auth.User, Note])
149
150 app.run()
151
152 After cleaning up the imports and declarations, we have something like the
153 following:
154
155 .. code-block:: python
156
157 import datetime
158 from flask import Flask
159
160 from peewee import *
161 from flask_peewee.auth import Auth
162 from flask_peewee.db import Database
163
164 # configure our database
165 DATABASE = {
166 'name': 'example.db',
167 'engine': 'peewee.SqliteDatabase',
168 }
169 DEBUG = True
170 SECRET_KEY = 'ssshhhh'
171
172 app = Flask(__name__)
173 app.config.from_object(__name__)
174
175 # instantiate the db wrapper
176 db = Database(app)
177
178 class Note(db.Model):
179 message = TextField()
180 created = DateTimeField(default=datetime.datetime.now)
181
182 # create an Auth object for use with our flask app and database wrapper
183 auth = Auth(app, db)
184
185 if __name__ == '__main__':
186 # Use the underlying Peewee database to create tables at startup
187 # if they do not exist.
188 with db.database:
189 db.database.create_tables([auth.User, Note])
190
191 app.run()
192
193
194 Managing content using the admin area
195 -------------------------------------
196
197 **Now** we're ready to add the admin. Place the following lines of code after
198 the initialization of the ``Auth`` class:
199
200 .. code-block:: python
201
202 from flask_peewee.admin import Admin
203
204 admin = Admin(app, auth)
205 admin.register(Note)
206
207 admin.setup()
208
209
210 We now have a functioning admin site! Of course, we'll need a user log in with,
211 so open up an interactive python shell in the directory alongside the app and run
212 the following:
213
214 .. code-block:: python
215
216 from app import auth
217 auth.User.create_table() # Make sure table created.
218 admin = auth.User(username='admin', email='', admin=True, active=True)
219 admin.set_password('admin')
220 admin.save()
221
222 It should now be possible to:
223
224 1. navigate to http://127.0.0.1:5000/admin/
225 2. enter in the username and password ("admin", "admin")
226 3. be redirected to the admin dashboard
227
228 .. image:: fp-getting-started.png
229
230 The dashboard is pretty empty right now. Go ahead and add a few notes (http://127.0.0.1:5000/admin/note/). If you navigate now to the note
231 modeladmin you will see something like this:
232
233 .. image:: fp-note-admin.png
234
235 This is pretty lousy so let's clean it up to display the message and when it was
236 published. We can do that by customizing the columns displayed. Edit the app with
237 the following changes:
238
239 .. code-block:: python
240
241 from flask_peewee.admin import Admin, ModelAdmin
242
243 class NoteAdmin(ModelAdmin):
244 columns = ('message', 'created',)
245
246 admin = Admin(app, auth)
247 admin.register(Note, NoteAdmin)
248 admin.setup()
249
250 Now our modeladmin should look more like this:
251
252 .. image:: fp-note-admin-2.png
253
254 Let's go ahead and add the ``auth.User`` model to the admin as well:
255
256 .. code-block:: python
257
258 admin.register(Note, NoteAdmin)
259 auth.register_admin(admin)
260 admin.setup()
261
262 The admin supports themes. Here is how to use the *crux* theme, for example:
263
264 .. code-block:: python
265
266 admin = Admin(app, auth, theme='crux')
267
268 .. image:: fp-crux.png
269
270
271 Exposing content using a REST API
272 ---------------------------------
273
274 Adding a REST API is very similar to how we added the :py:class:`Admin` interface.
275 We will create a :py:class:`RestAPI` object, and then register our project's models
276 with it. If we want to customize things, we can subclass :py:class:`RestResource`.
277
278 The first step, then, is to create the :py:class:`RestAPI` object:
279
280 .. code-block:: python
281
282 from flask_peewee.rest import RestAPI
283
284 # create a RestAPI container.
285 api = RestAPI(app)
286 api.setup()
287
288 This doesn't do anything yet, we need to register models with it first. Let's
289 register the ``Note`` model from earlier:
290
291 .. code-block:: python
292
293 # create a RestAPI container.
294 api = RestAPI(app)
295 api.register(Note)
296 api.setup()
297
298 Assuming your project is still running, try executing the following command (or
299 just browse to the url listed):
300
301 .. code-block:: console
302
303 $ curl http://127.0.0.1:5000/api/note/
304
305 You should see something like the following:
306
307 .. code-block:: javascript
308
309 {
310 "meta": {
311 "model": "note",
312 "page": 1,
313 "page_count": 1,
314 "object_count": 2,
315 "previous": "",
316 "next": ""
317 },
318 "objects": [
319 {
320 "id": 1,
321 "message": "This is a test note.",
322 "created": "2026-07-07T13:35:04"
323 },
324 {
325 "id": 2,
326 "message": "This is another test note.",
327 "created": "2026-07-07T13:35:18"
328 }
329 ]
330 }
331
332 Suppose we want it to also be possible for registered users to be able to POST
333 messages using the API. If you try and make a POST right now, you will get a
334 ``401`` response:
335
336 .. code-block:: console
337
338 $ curl -i -d '' http://127.0.0.1:5000/api/note/
339 HTTP/1.1 401 Unauthorized
340 Server: Werkzeug/3.2.0.dev0 Python/3.13.5
341 Date: Tue, 07 Jul 2026 18:41:49 GMT
342 WWW-Authenticate: Basic realm="Login Required"
343 Content-Type: text/html; charset=utf-8
344 Content-Length: 21
345 Vary: Cookie
346 Connection: close
347
348 This is because we have not configured any :py:class:`Authentication` method for
349 our :py:class:`RestAPI`.
350
351 .. note::
352 The default authentication mechanism for the API only accepts GET requests.
353 In order to handle POST/PUT/DELETE you will need to use a subclass of the
354 :py:class:`Authentication` class.
355
356 In order to allow users of the site to post notes, we will use the :py:class:`UserAuthentication`
357 subclass, which requires that API requests be made with HTTP Basic auth and that the
358 auth credentials match those of one of the ``auth.User`` models.
359
360 .. code-block:: python
361
362 from flask_peewee.rest import RestAPI, UserAuthentication
363
364 # instantiate the user auth
365 user_auth = UserAuthentication(auth)
366
367 # create a RestAPI container
368 api = RestAPI(app, default_auth=user_auth)
369
370 Now we can post new notes using a command-line tool like curl:
371
372 .. code-block:: console
373
374 $ curl -u admin:admin -d data='{"message": "hello api"}' http://127.0.0.1:5000/api/note/
375
376 {
377 "id": 3,
378 "message": "hello api",
379 "created": "2026-07-07T13:43:02.200138"
380 }
381
382 You can see that it returns a serialized copy of the new ``Note`` object.
383
384 .. note::
385 This is just a small example of what you can do with the Rest API -- refer to
386 the :ref:`Rest API docs <rest-api>` for more detailed information, including
387
388 * limiting access on a per-model basis
389 * customizing which fields are returned by the API
390 * filtering and querying using GET parameters