• No results found

Piccolo Admin. Release Daniel Townsend. Jul 22, 2021

N/A
N/A
Protected

Academic year: 2021

Share "Piccolo Admin. Release Daniel Townsend. Jul 22, 2021"

Copied!
31
0
0

Loading.... (view fulltext now)

Full text

(1)

Piccolo Admin

Release 0.14.0

Daniel Townsend

(2)
(3)
(4)
(5)

Piccolo Admin, Release 0.14.0

Piccolo Adminprovides a simple yet powerful admin interface on top of Piccolo tables - allowing you to easily add / edit / filter your data.

(6)
(7)

CHAPTER

ONE

INSTALLATION

Python 3.7 or above is required.

Install piccolo_admin, ideally inside avirtualenv. pip install piccolo_admin

1.1 Local demo

To run a demo locally: admin_demo

And then just launch localhost:8000 in your browser. Login using username: piccolo, password: piccolo123.

To see what happens behind the scenes, see piccolo_admin/example.py. In a few lines of code we are able to:

• Define our tables • Setup a database • Create a REST API

• Setup a web server and admin interface

(8)
(9)

CHAPTER

TWO

ASGI

Since the admin is anASGI app, you can either run it standalone like in the demo, or integrate it with a larger ASGI app.

Hint: Piccolo can help youcreate a new ASGI app- using piccolo asgi new. For example, using Starlette routes:

from piccolo_admin.endpoints import create_admin from starlette.routing import Router, Route import uvicorn

from my_project.tables import Director, Movie

# The `allowed_hosts` argument is required when running under HTTPS. It's used # for additional CSRF defence.

admin = create_admin([Director, Movie], allowed_hosts=['my_site.com'])

router = Router([

Route(path="/", endpoint=Hello), Mount(path="/admin/", app=admin), ])

if __name__ == '__main__': uvicorn.run(router)

2.1 FastAPI example

Here’s a complete example of a FastAPI app using Piccolo admin. # app.py

from fastapi import FastAPI

from piccolo.engine import engine_finder

from piccolo_admin.endpoints import create_admin from starlette.routing import Mount

from my_project.tables import Director, Movie

app = FastAPI(

(10)

(continued from previous page)

routes=[ Mount(

"/admin/", create_admin(

tables=[Director, Movie],

# Specify a different site name in the # admin UI (default Piccolo Admin)

site_name = "Mysite Admin",

# Required when running under HTTPS: # allowed_hosts=['my_site.com']

), ), ], )

@app.on_event("startup")

async def open_database_connection_pool(): engine = engine_finder()

await engine.start_connnection_pool()

@app.on_event("shutdown")

async def close_database_connection_pool(): engine = engine_finder()

await engine.close_connnection_pool()

To run app.py use:

uvicorn app:app --port 8000 --host 0.0.0.0

Now you can go tolocalhost:8000/adminand log in as an admin user (seeAuthenticationfor how to create users).

2.2 Source

class piccolo_admin.endpoints.create_admin(tables, auth_table=<class 'pic-colo.apps.user.tables.BaseUser'>, session_table=<class 'pic-colo_api.session_auth.tables.SessionsBase'>, session_expiry=datetime.timedelta(seconds=3600), max_session_expiry=datetime.timedelta(days=7), increase_expiry=datetime.timedelta(seconds=1200), page_size=15, read_only=False, rate_limit_provider=None, produc-tion=False, site_name='Piccolo Ad-min', auto_include_related=True, al-lowed_hosts=[])

Parameters

• tables (t.Sequence[t.Type[Table]]) – Each of the tables will be added to the admin.

• auth_table (t.Type[BaseUser]) – Either a BaseUser, or BaseUser subclass table, which is used for fetching users.

(11)

Piccolo Admin, Release 0.14.0

• session_table (t.Type[SessionsBase]) – Either a SessionBase, or SessionBase subclass table, which is used for storing and querying session tokens.

• session_expiry (timedelta) – How long a session is valid for.

• max_session_expiry (timedelta) – The maximum time a session is valid for, tak-ing into account any refreshes ustak-ing increase_expiry.

• increase_expiry (t.Optional[timedelta]) – If set, the session_expiry will be increased by this amount if it’s close to expiry.

• page_size (int) – The admin API paginates content - this sets the default number of results on each page.

• read_only (bool) – If True, all non auth endpoints only respond to GET requests - the admin can still be viewed, and the data can be filtered. Useful for creating online demos. • rate_limit_provider (t.Optional[RateLimitProvider]) – Rate limiting

middleware is used to protect the login endpoint against brute force attack. If not set, an InMemoryLimitProvider will be configured with reasonable defaults.

• production (bool) – If True, the admin will enforce stronger security - for example, the cookies used will be secure, meaning they are only sent over HTTPS.

• site_name (str) – Specify a different site name in the admin UI (default Piccolo Ad-min).

• auto_include_related (bool) – If a table has foreign keys to other tables, those tables will also be included in the admin by default, if not already specified. Otherwise the admin won’t work as expected.

(12)
(13)

CHAPTER

THREE

AUTHENTICATION

3.1 Session table

Piccolo admin usessession auth, which requires a Session database table.

Add piccolo_admin.piccolo_app to theAPP_REGISTRYin your piccolo_conf.py project file, then run migrations:

piccolo migrations forwards session_auth

To learn more about the Piccolo project files, check out the Piccolo ORMdocs.

3.2 Creating users

BaseUseris a Table you can use to store and authenticate your users. You need this table to be able to create users with admin privileges. BaseUser is shipped out of the box with Piccolo and you just need to run the migrations. Run the migrations:

piccolo migrations forwards user

Create a new user. piccolo user create

You will be prompted to enter a username, email address and password (you will be asked to enter your password twice for confirmation). Make sure you enter y when asked if it’s an admin user, otherwise the user won’t be able to login to the Piccolo admin GUI.

Warning: Non-admin users can’t login to the Piccolo admin GUI.

(14)
(15)

CHAPTER

FOUR

HELP TEXT

4.1 Columns

Sometimes you will want to provide hints to your users about what the form fields mean. Using this table as an example:

from piccolo.table import Table

from piccolo.columns import Varchar, Numeric

class Movie(Table):

name = Varchar(length=300)

box_office = Numeric(digits=(5, 1))

It isn’t immediately clear what box_office means. We can add a help_text attribute to the column: from piccolo.table import Table

from piccolo.columns import Varchar, Numeric

class Movie(Table):

name = Varchar(length=300)

box_office = Numeric(digits=(5, 1), help_text="In millions of US dollars.")

Piccolo Admin will then show a tooltip next to this field.

4.2 Tables

You can also provide help text about the table itself. from piccolo.table import Table

from piccolo.columns import Varchar, Numeric

class Movie(Table, help_text="Movies which were released in the cinema."): name = Varchar(length=300)

box_office = Numeric(digits=(5, 1), help_text="In millions of US dollars.")

(16)
(17)

CHAPTER

FIVE

CONTRIBUTING

The backend is just vanilla Python.

The front end is built using Vue.js. To make modifications, clone the repo, and cd into the admin_ui directory. Install the npm dependencies:

npm install

And then you can launch the admin as follows: npm run serve

It will auto refresh the UI as you make changes to the source files.

The UI needs an API to interact with - the easiest way to do this is to use the demo app. admin_demo

# Or alternatively

python -m piccolo_admin.example

# You can also populate lots of test data

python -m piccolo_admin.example --inflate=10000

# To find out all available options:

python -m piccolo_admin.example --help

You will need to configure a local webserver as a proxy - see extra/piccolo_admin.

5.1 Storybook

(18)
(19)

CHAPTER

SIX

API DOCUMENTATION

During development it is useful to have API documentation, showing all of the supported endpoints and parameters. After logging in to the Piccolo admin, you can go to /api/docs to seeSwagger docs, or /api/redoc to see Redoc docsfor the API.

(20)
(21)

CHAPTER

SEVEN

CHANGES

7.1 0.14.0

Using the swagger_ui endpoint from Piccolo API for the Swagger docs, so it works with the CSRF middleware.

7.2 0.13.2

Rewrote admin_demo command to expose configuration options on the command line.

7.3 0.13.1

• Bumped Node dependencies with security warnings.

• Slightly changed light mode styles (blue-grey sidebar instead of grey).

• Fixed the admin_demo command which is installed by setup.py - the path was wrong.

7.4 0.13.0

Modified the UI to support columns with a choices attribute set. A select input element is shown.

7.5 0.12.1

(22)

7.6 0.12.0

Added support for Array column type.

7.7 0.11.13

Exposing the site name on the login page, courtesy of sinisaos.

7.8 0.11.12

Added tooltips using the help_text attribute on Table.

7.9 0.11.11

Added tooltips using the help_text attribute on Column.

7.10 0.11.10

• The foreign key selector in the add and edit row forms now use the search based UI, courtesy of sinisaos. • Fixing a Vue JS warning about a route parameter being undefined.

7.11 0.11.9

• Exposed the host and port options directly in the sandbox CLI.

• Fixing a bug with read only mode. Was raising a 500 with disallowed HTTPS methods

7.12 0.11.8

• The foreign key selector in the sidebar is now search based, rather than a select element, courtesy of sinisaos. This makes the admin work better with very large data sets.

• Fixed a bug with nullable foreign keys. The value can now be set to null without a validation error.

(23)

Piccolo Admin, Release 0.14.0

7.13 0.11.7

Added an --inflate option to the CLI in example.py. This allows lots of dummy data to be added during develop-ment.

7.14 0.11.6

Fixing a bug with the date time picker on mobile devices - thanks sinisaos!

7.15 0.11.5

Fixing a bug where clearing the filters wasn’t clearing the duration widget’s value, as it uses a hidden input - thanks sinisaos!

7.16 0.11.4

Added missing trailing slash to table detail endpoints.

7.17 0.11.3

Fixing auth API URL - thanks sinisaos!

7.18 0.11.2

requirements.txt fixes

7.19 0.11.1

Updated Node dependencies, and fixed requirements clash with FastAPI and Starlette.

7.20 0.11.0

(24)

7.21 0.10.9

Fixing a bug with fetching meta information from the API (Piccolo version, site name etc). When a user isn’t logged in, it would fail. It now calls the API again after a successful login - courtesy of sinisaos.

7.22 0.10.8

• Can override the nav bar title (defaults to Piccolo Admin) - courtesy of sinisaos. • Other nav bar improvements, such as truncating long usernames.

7.23 0.10.7

• Added page size selector - courtesy of sinisaos. • Minor fixes

7.24 0.10.6

Added bulk deletion, and a custom widget for timedelta - courtesy of sinisaos.

7.25 0.10.5

Added a CSV export button to the row listing - courtesy of sinisaos.

7.26 0.10.4

• Removed dependency number for uvicorn and Hypercorn - only the very high level API is being used, which is unlikely to change, and was causing issues for some users when installing via Poetry.

• Bumped node dependencies.

7.27 0.10.3

Fixing packaging issues - add Python 3.8 classifier, and missing index.html file.

(25)

Piccolo Admin, Release 0.14.0

7.28 0.10.2

Subtle UI fixes - page selector, and setTimeout typo.

7.29 0.10.1

Added allowed_hosts argument to create_admin - otherwise CSRF middleware will block requests when running under HTTPS.

7.30 0.10.0

Using latest piccolo, and piccolo_api.

7.31 0.9.2

• Improved pagination when there’s lots of data. • Bumped node dependencies.

7.32 0.9.1

Bumped node requirements because of security warning.

7.33 0.9.0

Bumped node and pip requirements.

7.34 0.8.1

Bumped node and pip requirements.

7.35 0.8.0

(26)

7.36 0.7.0

Exposing more configuration options for session auth.

7.37 0.6.6

Disabling redirect on session auth.

7.38 0.6.5

Loosening requirements for Piccolo projects.

7.39 0.6.4

Bumped requirements.

7.40 0.6.3

Bumped requirements and added apps to piccolo_app migration dependencies.

7.41 0.6.2

Converted into a Piccolo app.

7.42 0.6.1

Bumped requirements.

7.43 0.6.0

Supporting piccolo 0.10.0.

(27)

Piccolo Admin, Release 0.14.0

7.44 0.5.1

Updated requirements.

7.45 0.5.0

Updated dependencies, and vendored remaining Javascript.

7.46 0.4.1

Using rate limit middleware on login endpoint. Auto including related tables. Using PATCH instead of PUT when editing a row. UI improvements.

7.47 0.4.0

Using textarea for Text database fields, using new API schema format, and various UI improvements.

7.48 0.3.8

Updated piccolo_api requirements.

7.49 0.3.7

UI improvements, and catching 404 errors.

7.50 0.3.6

Added ‘about’ modal to UI.

7.51 0.3.5

(28)

7.52 0.3.4

Added sandbox, for deploying demo version online.

7.53 0.3.3

UI improvements, including light mode. Support for pagination, and operators in filters.

7.54 0.3.2

Fixed typo - missing trailing slash.

7.55 0.3.1

Improved auth error handling, and adding defaults automatically when adding a new row.

7.56 0.3.0

Login is working, and various UI improvements.

7.57 0.2.0

Updated to work with Piccolo API code layout changes.

7.58 0.1.4

Making edit row work.

7.59 0.1.3

Added missing assets.

(29)

Piccolo Admin, Release 0.14.0

7.60 0.1.2

Added missing assets.

7.61 0.1.1

Fixing filters.

7.62 0.1.0

(30)
(31)

INDEX

C

References

Related documents

[r]

 The number of outsiders, D, increases with (i) higher proportion of low productivity enterprises, (ii) higher employment level at which regulation bites, (iii) higher wage,

and BANTHA MUSIC This arrangement © 2016 WARNER-TAMERLANE PUBLISHING CORP. and

It is proposed to install a plant to obtain refined vegetable oils of 4 tons every day or 1200 tons every year considering 300 working days... The requirement of plant and

This paper discusses some issues regarding networking technologies used as underlying communication infrastructures to support smart buildings.. SDN recently emerged as a

However, even in this article which deals exclusively with this subject, Griaule and Dieterlen only mention the actual existence of a star which really exists and does what the

(1) If personal checks, cashier's checks, traveler’s checks, payroll checks or counter checks are cashed at the cage, the gaming operation shall establish and comply with

Worksheet: 2 Chapter Name: Self &amp; Personality Issued on: Date of