This repository has been archived by the owner on Jul 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
manage.py
executable file
·320 lines (252 loc) · 8.11 KB
/
manage.py
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import contextlib
import click_spinner
import pydantic
import typer
from tabulate import tabulate
from app.db.initdb import init_shops
from app.enums import logenums, userenums
from app.main import app
from app.models import rolemodels, usermodels
from app.service import roleservice, userservice
from app.settings import settings
DB_URL = str(settings.POSTGRES_URL)
# Utilities
def create_database_if_not_exists():
"""
Create database if it doesn't already exist.
Runs migrations using alembic to bring it up to spec.
"""
from sqlalchemy_utils import create_database, database_exists
from alembic import command as alembic_cmd
from alembic.config import Config as AlembicConfig
alembic_cfg = AlembicConfig("alembic.ini")
if database_exists(DB_URL):
typer.secho("Database already exists.", fg="red")
raise typer.Abort
create_database(DB_URL)
# Run all migrations
alembic_cmd.upgrade(config=alembic_cfg, revision="head")
@contextlib.contextmanager
def existing_database():
"""
Context manager that returns a database session that closes.
"""
from sqlalchemy import orm
from sqlalchemy_utils import database_exists
from app.db.session import SessionLocal
if not database_exists(DB_URL):
typer.secho("Database does not exist.", fg="red")
raise typer.Abort
_db_session: orm.Session = SessionLocal()
yield _db_session
_db_session.close()
@contextlib.contextmanager
def catch_validation_err():
"""
Catch pydantic validation errors and display pretty message.
"""
try:
yield
except pydantic.ValidationError as e:
typer.secho(str(e), fg=typer.colors.RED, bold=True)
raise typer.Abort
class Messages:
success = typer.style("Success!", fg=typer.colors.GREEN, bold=True)
failed = typer.style("Failed!", fg=typer.colors.RED, bold=True)
confirm = typer.style(
"Are you sure you want to continue?", fg=typer.colors.BLUE, bold=True
)
# CLI commands
cli = typer.Typer(add_completion=False, no_args_is_help=True)
@cli.command()
def develop(
port: int = typer.Option(8000, help="Specify port to use."),
loglevel: logenums.LogLevel = typer.Option(
logenums.LogLevel.debug, case_sensitive=False, help="Set specific log level."
),
):
"""
Start a development server with reload.
"""
import uvicorn
from sqlalchemy_utils import database_exists
if not database_exists(DB_URL):
typer.secho("No database found, has it been initialised ?", fg="red")
raise typer.Abort
uvicorn.run(
"app.main:app",
reload=True,
log_level=loglevel,
port=port,
host=settings.SERVER_HOST,
)
@cli.command()
def routes():
"""
Display application routes and dependencies.
"""
tbl = []
for route in app.routes:
path = route.path
methods = ",".join(route.methods)
if hasattr(route, "dependencies"):
dependencies = [
str(d.dependency)
for d in route.dependencies
if hasattr(d, "dependency")
]
else:
dependencies = []
tbl.append([path, methods, dependencies])
typer.echo(
typer.style("\nApplication Endpoints\n", bold=True)
+ tabulate(tbl, headers=["Path", "Methods", "Dependencies"])
+ "\n"
)
@cli.command()
def shell():
"""
Starts an interactive shell with app object imported.
"""
# Local vars defined/imported will be available in shells global scope
import IPython
from app.main import app
IPython.embed()
@cli.command()
def config():
"""
Display application configuration.
"""
import json
data = json.loads(settings.json())
settings.schema()
table = [[k, v] for k, v in data.items()]
typer.echo(
typer.style("\nApplication Configuration\n", bold=True)
+ tabulate(table, headers=["Setting", "Value(s)"])
+ "\n"
)
@cli.command()
def createdb():
"""
Creates an empty database.
"""
create_database_if_not_exists()
typer.echo(Messages.success)
@cli.command()
def dropdb():
"""
Drop the existing database.
"""
from sqlalchemy_utils import drop_database, database_exists
typer.confirm(Messages.confirm, abort=True)
if not database_exists(DB_URL):
typer.secho("Database does not exist.", fg="red")
raise typer.Abort
drop_database(DB_URL)
typer.echo(Messages.success)
@cli.command(no_args_is_help=True)
def createuser(
email: str,
password: str,
first_name: str,
last_name: str,
status: userenums.UserStatus = typer.Argument(userenums.UserStatus.active),
role: str = typer.Argument(None),
):
"""
Create new user in the database.
EMAIL: Properly formatted email address.
PASSWORD: Users password.
FIRST_NAME: Users first name.
LAST_NAME: Users last name.
STATUS: Set user account status.
Optionally assign ROLE to user.
"""
with catch_validation_err():
user_in = usermodels.UserCreate(
email=email,
password=password,
first_name=first_name,
last_name=last_name,
status=status,
)
with existing_database() as db_session:
if role:
role_obj = roleservice.get_by_name(db_session=db_session, name=role)
if not role_obj:
typer.secho(
f"Role '{role}' does not exist!", fg=typer.colors.RED, bold=True
)
raise typer.Abort
userservice.create_with_role(
db_session=db_session, user_in=user_in, role=role_obj
)
else:
userservice.create(db_session=db_session, user_in=user_in)
typer.secho(Messages.success)
@cli.command(no_args_is_help=True)
def createrole(
name: str = typer.Argument(...), description: str = typer.Argument(None),
):
"""
Add role to database.
"""
with catch_validation_err():
role_in = rolemodels.RoleCreate(name=name, description=description)
with existing_database() as db_session:
roleservice.create(db_session=db_session, role_in=role_in)
typer.echo(Messages.success)
@cli.command()
def seeddb():
"""
Add fake data to database.
"""
import random
import faker
fake = faker.Faker()
# TODO: Add progress var from typer
with existing_database() as db_session:
with click_spinner.spinner():
# Create roles:
admin_role = roleservice.create(
db_session=db_session,
role_in=rolemodels.RoleCreate(
name="admin", description="Administrator privileges."
),
)
user_role = roleservice.create(
db_session=db_session,
role_in=rolemodels.RoleCreate(
name="user", description="Normal user privileges."
),
)
# Create 100 users with user role:
for _ in range(100):
userservice.create_with_role(
db_session=db_session,
user_in=usermodels.UserCreate(
email=fake.email(),
password="password",
first_name=fake.first_name(),
last_name=fake.last_name(),
status=random.choice(list(userenums.UserStatus)),
),
role=user_role,
)
# Create users with admin role
userservice.create_with_role(
db_session=db_session,
user_in=usermodels.UserCreate(
email="[email protected]",
password="password",
first_name=fake.first_name(),
last_name=fake.last_name(),
status=userenums.UserStatus.active,
),
role=admin_role,
)
init_shops(db_session=db_session)
typer.echo(Messages.success)
if __name__ == "__main__":
cli()