Skip to content

Commit

Permalink
documentation improvements (#166)
Browse files Browse the repository at this point in the history
* improve `SessionsBase` docs

* include viewcode Sphinx extension

* fix typo

* remove spaces

* add intro to openapi docs

* REST -> REST API

* add Piccolo Admin page to the docs
  • Loading branch information
dantownsend committed Jul 25, 2022
1 parent 6723091 commit 33ca725
Show file tree
Hide file tree
Showing 10 changed files with 72 additions and 20 deletions.
4 changes: 4 additions & 0 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@
"piccolo": ("https://piccolo-orm.readthedocs.io/en/latest/", None),
}

# -- Viewcode -------------------------------------------------------------

extensions += ["sphinx.ext.viewcode"]

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages. See the documentation for
Expand Down
3 changes: 1 addition & 2 deletions docs/source/crud/piccolo_crud.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ PiccoloCRUD

This creates an `ASGI <https://piccolo-orm.com/blog/introduction-to-asgi>`_ app,
which exposes the usual `CRUD <https://en.wikipedia.org/wiki/Create,_read,_update_and_delete>`_
methods on your Piccolo table, as well as some extras, via a `REST <https://en.wikipedia.org/wiki/Representational_state_transfer>`_
API.
methods on your Piccolo table, as well as some extras, via a `REST API <https://en.wikipedia.org/wiki/Representational_state_transfer>`_.

-------------------------------------------------------------------------------

Expand Down
2 changes: 1 addition & 1 deletion docs/source/csrf/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ endpoint, or just disable HTTP compression for your website.

-------------------------------------------------------------------------------

Module
Source
------

.. automodule:: piccolo_api.csrf.middleware
Expand Down
10 changes: 8 additions & 2 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,17 +41,23 @@ ASGI app, covering authentication, security, and more.
./advanced_auth/index

.. toctree::
:caption: Contributing
:caption: Piccolo Admin
:maxdepth: 1

./contributing/index
./piccolo_admin/index

.. toctree::
:caption: API Reference
:maxdepth: 1

./api_reference/index

.. toctree::
:caption: Contributing
:maxdepth: 1

./contributing/index

.. toctree::
:caption: Changes
:maxdepth: 1
Expand Down
2 changes: 2 additions & 0 deletions docs/source/openapi/index.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
OpenAPI
=======

Piccolo API has great support for viewing OpenAPI schemas using SwaggerUI.

Source
------

Expand Down
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 14 additions & 0 deletions docs/source/piccolo_admin/index.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
Piccolo Admin
=============

`Piccolo Admin <https://piccolo-admin.readthedocs.io/en/latest/>`_ is a
powerful web GUI which can be used to manage your data.

It's similar to tools like Django Admin and WordPress, but uses a rich Vue.js
front end, with a modern REST backend.

Piccolo API powers Piccolo Admin. If you want to see how the technologies
outlined here all work together, it's recommended to look at the Piccolo Admin
source code.

.. image:: ./images/piccolo_admin_screenshot.png
6 changes: 4 additions & 2 deletions docs/source/rate_limiting/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ Rate limiting is useful for certain public API endpoints. Examples are:
RateLimitingMiddleware
----------------------

Usage is simple - just wrap your ASGI app:

.. code-block:: python
from piccolo_api.rate_limiting.middleware import RateLimitingMiddleware
Expand Down Expand Up @@ -52,7 +54,7 @@ Stores the traffic data in memory. You can customise it as follows:
app = RateLimitingMiddleware(
my_asgi_app,
provider = InMemoryLimitProvider(
provider=InMemoryLimitProvider(
limit=1000,
timespan=300
),
Expand All @@ -68,7 +70,7 @@ specify this using the ``block_duration`` argument:
app = RateLimitingMiddleware(
my_asgi_app,
provider = InMemoryLimitProvider(
provider=InMemoryLimitProvider(
limit=1000,
timespan=300,
block_duration=300 # Blocked for 5 minutes
Expand Down
4 changes: 4 additions & 0 deletions docs/source/session_auth/tables.rst
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,7 @@ SessionsBase
.. currentmodule:: piccolo_api.session_auth.tables

.. autoclass:: SessionsBase
:class-doc-from: class
:members:
:undoc-members:
:member-order: groupwise
47 changes: 34 additions & 13 deletions piccolo_api/session_auth/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,24 @@

class SessionsBase(Table, tablename="sessions"):
"""
Use this table, or inherit from it, to create for a session store.
We set a hard limit on the expiry date - it can keep on getting extended
up until this value, after which it's best to invalidate it, and either
require login again, or just create a new session token.
Use this table, or inherit from it, to create a session store.
"""

token = Varchar(length=100, null=False)
user_id = Integer(null=False)
expiry_date: t.Union[Timestamp, datetime] = Timestamp(
#: Stores the session token.
token: Varchar = Varchar(length=100, null=False)

#: Stores the user ID.
user_id: Integer = Integer(null=False)

#: Stores the expiry date for this session.
expiry_date: Timestamp = Timestamp(
default=TimestampOffset(hours=1), null=False
)
max_expiry_date: t.Union[Timestamp, datetime] = Timestamp(

#: We set a hard limit on the expiry date - it can keep on getting extended
#: up until this value, after which it's best to invalidate it, and either
#: require login again, or just create a new session token.
max_expiry_date: Timestamp = Timestamp(
default=TimestampOffset(days=7), null=False
)

Expand All @@ -35,6 +40,9 @@ async def create_session(
expiry_date: t.Optional[datetime] = None,
max_expiry_date: t.Optional[datetime] = None,
) -> SessionsBase:
"""
Creates a session in the database.
"""
while True:
token = secrets.token_urlsafe(nbytes=32)
if not await cls.exists().where(cls.token == token).run():
Expand All @@ -54,20 +62,24 @@ async def create_session(
def create_session_sync(
cls, user_id: int, expiry_date: t.Optional[datetime] = None
) -> SessionsBase:
"""
A sync equivalent of :meth:`create_session`.
"""
return run_sync(cls.create_session(user_id, expiry_date))

@classmethod
async def get_user_id(
cls, token: str, increase_expiry: t.Optional[timedelta] = None
) -> t.Optional[int]:
"""
Returns the user_id if the given token is valid, otherwise None.
Returns the ``user_id`` if the given token is valid, otherwise
``None``.
:param increase_expiry:
If set, the `expiry_date` will be increased by the given amount
If set, the ``expiry_date`` will be increased by the given amount
if it's close to expiring. If it has already expired, nothing
happens. The `max_expiry_date` remains the same, so there's a hard
limit on how long a session can be used for.
happens. The ``max_expiry_date`` remains the same, so there's a
hard limit on how long a session can be used for.
"""
session: SessionsBase = (
await cls.objects().where(cls.token == token).first().run()
Expand All @@ -92,12 +104,21 @@ async def get_user_id(

@classmethod
def get_user_id_sync(cls, token: str) -> t.Optional[int]:
"""
A sync wrapper around :meth:`get_user_id`.
"""
return run_sync(cls.get_user_id(token))

@classmethod
async def remove_session(cls, token: str):
"""
Deletes a matching session from the database.
"""
await cls.delete().where(cls.token == token).run()

@classmethod
def remove_session_sync(cls, token: str):
"""
A sync wrapper around :meth:`remove_session`.
"""
return run_sync(cls.remove_session(token))

0 comments on commit 33ca725

Please sign in to comment.