### Access Model Context in Setup Method
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/models.md
The `setup` method provides access to the model's database, table, and fields, allowing for context-aware initialization.
```python
def setup(self):
# you can access the database, the table and its fields
db = self.db
table = self.table
field = self.table.fieldname
```
--------------------------------
### Emmett Web App with ORM and Authentication
Source: https://github.com/emmett-framework/emmett/blob/master/README.md
This example demonstrates setting up a basic Emmett web application. It includes ORM model definition, database configuration, pipeline setup, authentication, and a service endpoint for fetching tasks. Ensure the database URI is correctly configured.
```python
from emmett import App, request, response
from emmett.orm import Database, Model, Field
from emmett.tools import service, requires
class Task(Model):
name = Field.string()
is_completed = Field.bool(default=False)
app = App(__name__)
app.config.db.uri = "postgres://user:password@localhost/foo"
db = Database(app)
db.define_models(Task)
app.pipeline = [db.pipe]
def is_authenticated():
return request.headers.get("api-key") == "foobar"
def not_authorized():
response.status = 401
return {'error': 'not authorized'}
@app.route(methods='get')
@requires(is_authenticated, otherwise=not_authorized)
@service.json
async def todo():
page = request.query_params.page or 1
tasks = Task.where(
lambda t: t.is_completed == False
).select(paginate=(page, 20))
return {'tasks': tasks}
```
--------------------------------
### Setup Admin User Command
Source: https://github.com/emmett-framework/emmett/blob/master/docs/tutorial.md
Define a command-line function to create an admin user, an admin group, and assign membership.
```python
@app.command('setup')
def setup():
with db.connection():
# create the user
user = User.create(
email="doc@emmettbrown.com",
first_name="Emmett",
last_name="Brown",
password="fluxcapacitor"
)
# create an admin group
admins = auth.create_group("admin")
# add user to admins group
auth.add_membership(admins, user.id)
db.commit()
```
--------------------------------
### Initialize Emmett Auth Module
Source: https://github.com/emmett-framework/emmett/blob/master/docs/auth.md
Basic setup for the Emmett Auth module, including app configuration, database setup, and pipeline integration. Requires session management and a Database instance.
```python
from emmett import App
from emmett.orm import Database
from emmett.tools.auth import Auth, AuthUser
from emmett.sessions import SessionManager
app = App(__name__)
app.config.db.uri = "sqlite://storage.sqlite"
app.config.auth.hmac_key = "mysupersecretkey"
app.config.auth.single_template = True
class User(AuthUser):
pass
db = Database(app)
auth = Auth(app, db, user_model=User)
app.pipeline = [
SessionManager.cookies('myverysecretkey'),
db.pipe,
auth.pipe
]
auth_routes = auth.module(__name__)
```
--------------------------------
### Install Emmett using pip
Source: https://github.com/emmett-framework/emmett/blob/master/docs/installation.md
Install the Emmett framework within the activated virtual environment using pip. This command fetches and installs the latest version of Emmett and its dependencies.
```bash
pip install emmett
```
--------------------------------
### Create a Basic 'Hello World' Emmett Application
Source: https://github.com/emmett-framework/emmett/blob/master/docs/quickstart.md
This snippet shows the minimal setup for an Emmett application. Save this as *app.py* and run it using the 'emmett develop' command.
```python
from emmett import App
app = App(__name__)
@app.route("/")
async def hello():
return "Hello world!"
```
--------------------------------
### Basic Translation Setup in Emmett
Source: https://github.com/emmett-framework/emmett/blob/master/docs/languages.md
Initializes an Emmett application and demonstrates basic string translation using the T object. The translated string is then returned in a dictionary.
```python
from emmett import App, T
app = App(__name__)
@app.route("/")
async def index():
hello = T('Hello, my dear!')
return dict(hello=hello)
```
--------------------------------
### Make a GET Request with Redirects Enabled
Source: https://github.com/emmett-framework/emmett/blob/master/docs/testing.md
Use the `follow_redirects=True` option to make a GET request that will automatically follow any redirects.
```python
client.get('/', follow_redirects=True)
```
--------------------------------
### Session Management with Emmett
Source: https://context7.com/emmett-framework/emmett/llms.txt
Demonstrates session management using Emmett's SessionManager. The example shows how to configure session storage using files or Redis.
```python
# app.pipeline = [SessionManager.files(expire=3600)]
# --- Redis-based (shared across workers) ---
# red = Redis(host="localhost", port=6379)
# app.pipeline = [SessionManager.redis(red, expire=3600)]
@app.route("/counter")
async def counter():
session.visits = (session.visits or 0) + 1
session.user_id = 42 # store anything picklable
return {"visits": session.visits}
```
--------------------------------
### Renoir Template Example
Source: https://context7.com/emmett-framework/emmett/llms.txt
Example of a Renoir template for displaying posts, including extending a layout, iterating over items, and conditional rendering.
```html
{{extend 'layout.html'}}
{{block content}}
{{=title}}
{{for post in posts:}}
{{=post.title}}
{{=post.body}}
{{pass}}
{{if current.auth.is_logged():}}
Write a post
{{pass}}
{{end}}
```
--------------------------------
### Initialize Emmett App with Database and Modules
Source: https://github.com/emmett-framework/emmett/blob/master/docs/patterns.md
Initialize an Emmett application with a database connection and configure default URL namespaces. This setup is typical for MVC patterns.
```python
from emmett import App
from emmett.orm import Database
app = App(__name__)
app.config.url_default_namespace = "main"
db = Database()
from .models.user import User
from .models.article import Post
db.define_models(User, Post)
from .controllers import main, api
```
--------------------------------
### Using an Emmett Extension
Source: https://github.com/emmett-framework/emmett/blob/master/docs/extensions.md
Demonstrates how to import, configure, and use an extension within an Emmett application. Ensure the extension is installed and declared as a dependency.
```python
from emmett import App
from emmett_foo import Foo
app = App(__name__)
# configure the extension
app.config.Foo.someparam = "something"
# add the extension to our app
app.use_extension(Foo)
# access extension attributes and methods
app.ext.Foo.bar()
```
--------------------------------
### Basic App Setup with Templating
Source: https://github.com/emmett-framework/emmett/blob/master/docs/templates.md
Sets up a basic Emmett application and a route that renders an HTML template. The template expects a 'message' variable from the Python function's return dictionary.
```python
from emmett import App
app = App(__name__)
@app.route("/")
async def echo(msg):
return dict(message=msg)
```
--------------------------------
### DateInjector Example
Source: https://context7.com/emmett-framework/emmett/llms.txt
Demonstrates how to create a custom injector to add helper functions to template contexts. The DateInjector provides a `pretty` method for formatting dates.
```APIDOC
## Injectors
`Injector` objects add helper functions and values into every template context automatically, avoiding repetition across route return dicts.
```python
from emmett import App, Injector
import pendulum
app = App(__name__)
class DateInjector(Injector):
namespace = "dates" # available in templates as dates.pretty(...)
def pretty(self, dt):
diff = pendulum.now().diff(dt)
if diff.in_hours() < 1:
return f"{diff.in_minutes()} minutes ago"
return dt.format("YYYY-MM-DD HH:mm")
app.injectors = [DateInjector()]
# In any template: {{ =dates.pretty(post.created_at) }}
```
```
--------------------------------
### Dockerfile for Emmett Application
Source: https://github.com/emmett-framework/emmett/blob/master/docs/deployment.md
A sample Dockerfile to containerize an Emmett application. It uses a slim Python image and installs dependencies before copying the application code.
```docker
FROM python:3.9-slim
RUN mkdir -p /usr/src/deps
COPY requirements.txt /usr/src/deps
WORKDIR /usr/src/deps
RUN pip install --no-cache-dir -r /usr/src/deps/requirements.txt
COPY ./ /app
WORKDIR /app
EXPOSE 8000
CMD [ "emmett", "serve" ]
```
--------------------------------
### Run Emmett Development Server
Source: https://github.com/emmett-framework/emmett/blob/master/docs/quickstart.md
Execute this command in your terminal to start the Emmett development server. It will automatically detect and run your application.
```bash
> emmett develop
App running on 127.0.0.1:8000
```
--------------------------------
### Italian Language Translation File
Source: https://github.com/emmett-framework/emmett/blob/master/docs/languages.md
Example of a JSON file containing translations for the 'Hello, my dear!' string into Italian. This file should be placed in the 'languages' directory.
```json
{
"Hello, my dear!": "Ciao, mio caro!"
}
```
--------------------------------
### Send Welcome Email After User Insert
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/callbacks.md
This example demonstrates sending a welcome email after a new user is successfully inserted into the database. It utilizes an `after_commit` callback filtered for the `insert` operation.
```python
class User(Model):
email = Field()
@after_commit.operation(TransactionOps.insert)
def _send_welcome_email(self, ctx):
my_queue_system.send_welcome_email(ctx.return_value)
```
--------------------------------
### Initialize Auth Module Routes
Source: https://github.com/emmett-framework/emmett/blob/master/docs/tutorial.md
Initializes the authentication module to expose signup and signin routes. This leverages Emmett's application module system for convenient setup.
```python
auth_routes = auth.module(__name__)
```
--------------------------------
### Simple Echo WebSocket Example
Source: https://github.com/emmett-framework/emmett/blob/master/docs/websocket.md
Implement a basic echo websocket that receives a message and sends it back to the client. The connection closes when the function returns.
```python
from emmett import websocket
@app.websocket()
async def echo():
while True:
message = await websocket.receive()
await websocket.send(message)
```
--------------------------------
### Applying PeriodPipe to Routes
Source: https://github.com/emmett-framework/emmett/blob/master/docs/pipeline.md
Examples of applying the PeriodPipe with different day durations (1, 7, 30) to specific routes, demonstrating parameter injection.
```python
@app.route("/foo/daily/", pipeline=[PeriodPipe(1)])
async def foo_daily(start, end):
# code
@app.route("/foo/weekly/", pipeline=[PeriodPipe(7)])
async def foo_weekly(start, end):
# code
@app.route("/foo/monthly/", pipeline=[PeriodPipe(30)])
async def foo_monthly(start, end):
# code
```
--------------------------------
### Example Usage of Custom Model Method
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/models.md
Demonstrates how to call a custom class method defined on a model to perform an action, such as updating records.
```python
>>> Notification.read_all(my_user)
3
```
--------------------------------
### Route with Parameter-Injecting Pipeline
Source: https://context7.com/emmett-framework/emmett/llms.txt
Example of attaching a pipeline to a route, using PeriodPipe to modify route parameters.
```python
app.pipeline = [SessionManager.cookies("key"), ApiKeyPipe()]
@app.route("/report/", pipeline=[PeriodPipe(7)])
async def weekly_report(start, end):
return {"from": str(start), "to": str(end)}
```
--------------------------------
### Run Emmett Development Server
Source: https://github.com/emmett-framework/emmett/blob/master/docs/cli.md
Use this command to start a development server for your Emmett application. If your application cannot be auto-detected, specify its import path using the --app or -a flag.
```bash
> emmett develop
```
```bash
> emmett -a myapp.py develop
```
--------------------------------
### Define Main Controller Route
Source: https://github.com/emmett-framework/emmett/blob/master/docs/patterns.md
Example of a main controller file in an MVC structure. It defines the root route for the application.
```python
from .. import app
@app.route("/")
async def index():
# code
```
--------------------------------
### Handling File Uploads
Source: https://github.com/emmett-framework/emmett/blob/master/docs/request.md
Illustrates how to access and process uploaded files using the `request.files` attribute. It shows examples of reading file content and asynchronously saving the file.
```python
@app.route()
async def multipart_load():
files = await request.files
# at this point you can either:
# i) read all the file contents
data = files.myfile.read()
# ii) read up to 4k of the file contents
data = files.myfile.read(4096)
# iii) store the file
await files.myfile.save(f"some/destination/{files.myfile.filename}")
```
--------------------------------
### Equivalent Query for Combined Scopes
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/scopes.md
This shows the equivalent query using `where` and lambda functions for the combined scopes example. It demonstrates how scopes simplify complex query construction.
```python
Post.where(
lambda p:
(p.state == Post.STATES['published']) &
(p.created_at >= datetime(2015, 1, 15)) &
(p.created_at < datetime(2015, 1, 16))
)
```
--------------------------------
### Create Table Migration
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/migrations.md
Defines a migration to create a new 'tags' table with an 'id' and a 'name' column. This is an example of an 'up' method in a migration file.
```python
from emmett.orm import migrations
class Migration(migrations.Migration):
revision = '4dee31071bf8'
revises = '4ceb82ecd8e4'
def up(self):
self.create_table(
'tags',
migrations.Column('id', 'id'),
migrations.Column('name', 'string', length=512))
def down(self):
self.drop_table('tags')
```
--------------------------------
### Emmett WebSocket Implementation
Source: https://context7.com/emmett-framework/emmett/llms.txt
Shows how to implement WebSocket routes using @app.websocket(). The example includes an echo server and a chat room with query parameter support. It also demonstrates building WebSocket URLs.
```python
from emmett import App, websocket
app = App(__name__)
# Echo server
@app.websocket("/ws/echo")
async def echo():
while True:
message = await websocket.receive()
if message is None:
break
await websocket.send(f"Echo: {message}")
# Chat room example with query params
@app.websocket("/ws/chat")
async def chat():
room = websocket.query_params.room or "general"
await websocket.send(f"Joined room: {room}")
while True:
msg = await websocket.receive()
if msg is None:
break
await websocket.send(f"[{room}] {msg}")
# Build WebSocket URLs
from emmett import url
ws_url = url.ws("echo") # ws://host/ws/echo
```
--------------------------------
### Advanced Pipeline Composition with Authentication
Source: https://github.com/emmett-framework/emmett/blob/master/docs/pipeline.md
Combine different authentication strategies for front-end and API modules within the pipeline. This example shows how to apply a default authentication for the front and a custom one for secure APIs.
```python
front = app.module(__name__, 'front')
front.pipeline = [
SessionManager.cookies('GreatScott!'),
auth.pipe
]
apis = app.module(__name__, 'apis', url_prefix='api')
apis.pipeline = [ServicePipe('json')]
secure_apis = apis.module(__name__, 'secure')
secure_apis.pipeline[MyAuthPipe()]
```
--------------------------------
### Define a Custom Emmett Command
Source: https://github.com/emmett-framework/emmett/blob/master/docs/cli.md
Add custom commands to your Emmett application by decorating a function with @app.command. This example shows how to create a 'setup' command.
```python
from emmett import App
app = App(__name__)
@app.command('setup')
def setup():
# awesome code to initialize your app
```
--------------------------------
### Define and Use a Database Model
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm.md
This snippet demonstrates how to set up an SQLite database, define a 'Post' model with fields, register the database pipeline, and query posts by author.
```python
from emmett import App
from emmett.orm import Database, Model, Field
app = App(__name__)
app.config.db.uri = "sqlite://storage.sqlite"
class Post(Model):
author = Field()
title = Field()
body = Field.text()
db = Database(app)
db.define_models(Post)
app.pipeline = [db.pipe]
@app.route('/posts/')
def post_by(author):
posts = db(Post.author == author).select()
return dict(posts=posts)
```
--------------------------------
### Initialize Database and Auth
Source: https://github.com/emmett-framework/emmett/blob/master/docs/tutorial.md
Instantiate Database and Auth modules, linking them with the application and defining user models.
```python
from emmett.orm import Database
from emmett.tools import Auth
db = Database(app)
auth = Auth(app, db, user_model=User)
db.define_models(Post, Comment)
```
--------------------------------
### Migration File Structure
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/migrations.md
Generated migration files contain Python code defining the `up` and `down` methods for schema changes. This example shows table creation for users and authentication modules.
```python
"""First migration
Migration ID: fe68547ce244
Revises:
Creation Date: 2017-03-09 16:31:24.333823
"""
from emmett.orm import migrations
class Migration(migrations.Migration):
revision = 'fe68547ce244'
revises = None
def up(self):
self.create_table(
'users',
migrations.Column('id', 'id'),
migrations.Column('created_at', 'datetime'),
migrations.Column('updated_at', 'datetime'),
migrations.Column('email', 'string', length=255),
migrations.Column('password', 'password', length=512),
migrations.Column('registration_key', 'string', default='', length=512),
migrations.Column('reset_password_key', 'string', default='', length=512),
migrations.Column('registration_id', 'string', default='', length=512),
migrations.Column('first_name', 'string', notnull=True, length=128),
migrations.Column('last_name', 'string', notnull=True, length=128))
self.create_table(
'auth_groups',
migrations.Column('id', 'id'),
migrations.Column('created_at', 'datetime'),
migrations.Column('updated_at', 'datetime'),
migrations.Column('role', 'string', default='', length=255),
migrations.Column('description', 'text'))
self.create_table(
'auth_memberships',
migrations.Column('id', 'id'),
```
--------------------------------
### Initialize virtualenv Environment
Source: https://github.com/emmett-framework/emmett/blob/master/docs/installation.md
Create and navigate to a project directory, then initialize a virtual environment named .venv. This isolates project dependencies.
```bash
mkdir -p myproject
cd myproject
python -m venv .venv
```
--------------------------------
### Low-Level Cache API: Get Contents
Source: https://github.com/emmett-framework/emmett/blob/master/docs/caching.md
Access cached contents directly using the `get` method. Returns `None` if no content is available for the given key.
```python
value = cache.get('key')
```
--------------------------------
### Initialize Cache with Multiple Backends
Source: https://context7.com/emmett-framework/emmett/llms.txt
Configure the `Cache` tool with multiple backends like RAM and Redis. Specify a default backend and individual TTLs for each.
```python
from emmett import App
from emmett.cache import Cache, RamCache, RedisCache
app = App(__name__)
# Correct multi-backend setup
cache = Cache(
ram=RamCache(default_expire=60),
redis=RedisCache(host="localhost", port=6379, default_expire=300),
default="ram",
)
```
--------------------------------
### Count all records
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/operations.md
Use the `count()` method on a set to get the total number of records.
```python
>>> Event.all().count()
3
```
--------------------------------
### Define Event Model
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/operations.md
Example of defining a model for events with various field types.
```python
class Event(Model):
name = Field()
location = Field()
participants = Field.int()
happens_at = Field.datetime()
```
--------------------------------
### Configure Authentication System
Source: https://context7.com/emmett-framework/emmett/llms.txt
Set up the `Auth` tool by configuring the application and database. This includes setting the HMAC key, database URI, and disabling email verification if needed.
```python
from emmett import App, url, redirect
from emmett.orm import Database, Field
from emmett.sessions import SessionManager
from emmett.tools import requires
from emmett.tools.auth import Auth, AuthUser
app = App(__name__)
app.config.db.uri = "sqlite://storage.sqlite"
app.config.auth.hmac_key = "change-me-in-production"
app.config.auth.single_template = True
app.config.auth.registration_verification = False # disable email verify
class User(AuthUser):
bio = Field.text()
form_profile_rw = {"bio": True} # show in profile form only
db = Database(app)
auth = Auth(app, db, user_model=User)
app.pipeline = [
SessionManager.cookies("session-secret"),
db.pipe,
auth.pipe,
]
```
--------------------------------
### Query Events Not in New York
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/operations.md
Example of using the '!=' operator to exclude events from a specific location.
```python
db(Event.location != "New York")
```
--------------------------------
### Initialize Cache with Multiple Systems
Source: https://github.com/emmett-framework/emmett/blob/master/docs/caching.md
Instantiate the Cache class with different caching backends. Ensure all necessary backend classes are imported.
```python
from emmett.cache import Cache, RamCache, DiskCache, RedisCache
cache = Cache(
ram=RamCache(),
disk=DiskCache(),
redis=RedisCache()
)
```
--------------------------------
### Apply Database Migrations
Source: https://github.com/emmett-framework/emmett/blob/master/docs/tutorial.md
Create the databases directory and apply pending database migrations using the emmett CLI.
```bash
> mkdir -p databases
> emmett migrations up
```
--------------------------------
### PeriodPipe for Parameter Injection
Source: https://context7.com/emmett-framework/emmett/llms.txt
A pipe that injects a calculated 'end' date based on a 'start' date and a duration.
```python
from datetime import timedelta
class PeriodPipe(Pipe):
def __init__(self, days):
self.delta = timedelta(days=days)
async def pipe(self, next_pipe, **kwargs):
kwargs["end"] = kwargs["start"] + self.delta
return await next_pipe(**kwargs)
```
--------------------------------
### Combine Date Range Conditions
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/operations.md
Example of combining conditions to query events within a specific date range.
```python
db(
(Event.happens_at >= datetime(1955, 10, 5)) &
(Event.happens_at < datetime(1955, 10, 6))
)
```
--------------------------------
### Define City Model with Geography Field
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/operations.md
Example of defining a model with a geography field for storing location data.
```python
class City(Model):
name = Field.string()
location = Field.geography("POINT")
```
--------------------------------
### Initialize Multiple Database Instances
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/connecting.md
Initialize multiple Database instances for different databases. The second instance is configured using a specific config object from the application's config.
```python
app.config.db.uri = "postgres://localhost/mydb"
app.config.db2.uri = "mongodb://localhost/mydb"
db = Database(app)
db2 = Database(app, app.config.db2)
```
--------------------------------
### Initialize Database Instance
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/connecting.md
Initialize the Database class with your application instance. This instance will be the primary access point for database operations.
```python
from emmett.orm import Database
db = Database(app)
```
--------------------------------
### App Initialization and Configuration
Source: https://context7.com/emmett-framework/emmett/llms.txt
Initialize the Emmett App and configure settings using dot-notation or YAML files. This is the entry point for any Emmett application.
```python
from emmett import App
app = App(__name__)
# Inline configuration with sub-namespace auto-creation
app.config.db.uri = "postgres://user:password@localhost/mydb"
app.config.auth.hmac_key = "supersecretkey"
app.config.static_version_urls = True
app.config.static_version = "1.0.0"
# Or load from YAML files placed in the config/ directory
# app.config_from_yaml('app.yml')
# app.config_from_yaml('db.yml', 'db')
if __name__ == "__main__":
# Run with: emmett develop
pass
```
--------------------------------
### Defining a Datetime Field
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/models.md
Example of defining a datetime field using Field.datetime(). Emmett maps this to the appropriate datetime column type in the database.
```python
started = Field.datetime()
```
--------------------------------
### Define a Model with States
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/scopes.md
Define a model with fields and a dictionary for state mappings. This setup is often a prerequisite for defining scopes related to these states.
```python
class Post(Model):
title = Field()
body = Field.text()
created_at = Field.datetime()
changed_at = Field.datetime()
state = Field.int()
STATES = {'draft': 0, 'published': 1, 'retired': 2}
validation = {
'state': {'in': {
'set': list(STATES.values()),
'labels': list(STATES)}}
}
```
--------------------------------
### Create an Application Module
Source: https://github.com/emmett-framework/emmett/blob/master/docs/app_and_modules.md
Create a new application module using `app.module()`. This allows grouping routes with common prefixes or hostnames.
```python
blog = app.module(__name__, name="blog", url_prefix="blog")
```
--------------------------------
### Define Event Model
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/operations.md
Defines a sample `Event` model with fields for name, location, participants, and event time. This model is used for subsequent examples.
```python
class Event(Model):
name = Field(notnull=True)
location = Field(notnull=True)
participants = Field.int(default=0)
happens_at = Field.datetime()
```
--------------------------------
### Respond with File Content
Source: https://github.com/emmett-framework/emmett/blob/master/docs/response.md
Use response.wrap_file to create a response from a file path. Use response.wrap_io to create a response from a file-like object.
```python
@app.route("/file/")
async def file(name):
return response.wrap_file(f"assets/{name}")
@app.route("/io/")
async def io(name):
with open(f"assets/{name}", "rb") as f:
return response.wrap_io(f)
```
--------------------------------
### Basic App with Templating
Source: https://github.com/emmett-framework/emmett/blob/master/docs/quickstart.md
Set up a simple Emmett application that routes a URL parameter to an HTML template. The dictionary returned by the route function serves as the template context.
```python
from emmett import App
app = App(__name__)
@app.route("/")
async def echo(msg):
return dict(message=msg)
```
```html
{{=message}}
```
--------------------------------
### Configure Multiple Modules with Different Pipelines
Source: https://github.com/emmett-framework/emmett/blob/master/docs/app_and_modules.md
Set up different pipelines for modules, potentially including custom authentication pipes. Pipelines are composed sequentially from parent to child modules.
```python
from emmett.tools import ServicePipe
apis = app.module(__name__, 'apis', url_prefix='apis')
apis.pipeline = [ServicePipe('json')]
v1_apis = apis.module(__name__, 'v1', url_prefix='v1')
v1_apis.pipeline = [SomeAuthPipe()]
v2_apis = apis.module(__name__, 'v2', url_prefix='v2')
v2_apis.pipeline = [AnotherAuthPipe()]
```
--------------------------------
### Access Related Data with has_many
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/relations.md
The `has_many` helper provides access to a collection of related records. This example shows how to access the patients associated with a doctor.
```python
doctor_bishop = db.Doctor(name="Bishop")
dr.bishop.patients
```
--------------------------------
### Write a Basic Test with Pytest
Source: https://github.com/emmett-framework/emmett/blob/master/docs/testing.md
This fixture and test function demonstrate how to set up a test client and verify the application's response for an empty database scenario.
```python
import pytest
from bloggy import app
@pytest.fixture()
def client():
return app.test_client()
def test_empty_db(client):
rv = client.get('/')
assert 'No posts here so far' in rv.data
```
--------------------------------
### Run Emmett Application with Included Server
Source: https://github.com/emmett-framework/emmett/blob/master/docs/deployment.md
Use the `emmett serve` command to run your application in production. Inspect all available options using the `--help` flag.
```bash
emmett serve --host 0.0.0.0 --port 80
```
--------------------------------
### Basic ORM Queries and Aggregations
Source: https://context7.com/emmett-framework/emmett/llms.txt
Demonstrates basic record retrieval, filtering with AND/OR, fetching single records, and performing aggregations like counts. Use `select()` for queries, `where()` for filtering, and aggregation functions for summaries.
```python
all_posts = Post.all().select()
recent = Post.where(lambda p: p.created_at >= datetime(2024, 1, 1)).select(
orderby=~Post.created_at, paginate=(1, 10))
```
```python
results = db(
(Post.title.contains("python", case_sensitive=False)) &
(Post.created_at.year() == 2024)
).select(orderby=Post.created_at)
```
```python
user = User.get(email="alice@example.com")
post = Post.get(1)
first = Post.first()
```
```python
from emmett.orm import Field
count = Post.id.count()
rows = db(
Post.created_at.year() == 2024
).select(
Post.user, count,
groupby=Post.user,
orderby=~count
)
for row in rows:
print(row.posts.user, row[count])
```
```python
page2 = Post.all().select(paginate=(2, 25)) # page 2, 25 per page
```
```python
ids = [1, 2, 3]
posts = db(Post.id.belongs(ids)).select()
```
--------------------------------
### Define API Module Route
Source: https://github.com/emmett-framework/emmett/blob/master/docs/patterns.md
Example of an API controller file within an MVC structure. It defines a module with a URL prefix for API endpoints.
```python
from .. import app
api = app.module(__name__, 'api', url_prefix='api')
@api.route()
async def a():
# code
```
--------------------------------
### after_destroy Callback Example
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/callbacks.md
The `after_destroy` callback is executed after a record has been destroyed. The decorated method receives the destroyed record. This callback is invoked after the `after_delete` callback.
```python
class Cart(Model):
has_many({"elements": "CartElement"})
updated_at = Field.datetime(default=now, update=now)
class CartElement(Model):
belongs_to("cart")
@after_destroy
def _update_cart(self, row):
row.cart.save()
```
--------------------------------
### Load Configuration from YAML Files
Source: https://github.com/emmett-framework/emmett/blob/master/docs/app_and_modules.md
Load application configuration from YAML files using `config_from_yaml()`. You can specify a namespace to load the configuration into.
```python
app.config_from_yaml('app.yml')
app.config_from_yaml('db.yml', 'db')
```
--------------------------------
### before_destroy Callback Example
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/callbacks.md
The `before_destroy` callback is called just before a record is destroyed. The decorated method receives the record that is about to be destroyed. This callback is invoked before the `before_delete` callback.
```python
class Product(Model):
name = Field.string()
price = Field.float(default=0.0)
class CartElement(Model):
belongs_to("product")
quantity = Field.int(default=1)
price_denorm = Field.float(default=0.0)
@before_destroy
def _clear_element(self, row):
row.quantity = 0
row.price_denorm = 0
```
--------------------------------
### Configure Database Connection Details
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/connecting.md
Configure individual database connection parameters like adapter, host, user, password, and database name. This is useful for complex configurations or when not using a URI.
```python
app.config.db.adapter = 'postgres'
app.config.db.host = 'localhost'
app.config.db.user = 'username'
app.config.db.password = 'yourpassword'
app.config.db.database = 'database'
```
--------------------------------
### Define a Route in Views Module
Source: https://github.com/emmett-framework/emmett/blob/master/docs/patterns.md
Define routes in a separate views.py file within your Emmett package. This example shows a basic index route.
```python
from . import app
@app.route("/")
async def index():
# some code
```
--------------------------------
### Initialize Emmett App in Package
Source: https://github.com/emmett-framework/emmett/blob/master/docs/patterns.md
Use this in your __init__.py file to create an Emmett application instance within a package structure. Ensure all routes are imported after app initialization.
```python
from emmett import App
app = App(__name__)
from . import views
```
--------------------------------
### Configure Application Pipeline
Source: https://github.com/emmett-framework/emmett/blob/master/docs/tutorial.md
Add SessionManager, database pipe, and authentication pipe to the application's request pipeline.
```python
from emmett.sessions import SessionManager
app.pipeline = [
SessionManager.cookies('GreatScott'),
db.pipe,
auth.pipe
]
```
--------------------------------
### Select Distinct Records
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/operations.md
Use the `distinct` option in the `select` method to get unique records based on the specified fields, equivalent to grouping by all selected fields.
```python
db(Event.happens_at.year() == 1955).select(
Event.location,
distinct=True)
```
--------------------------------
### Configure Session Storage with Cookies
Source: https://github.com/emmett-framework/emmett/blob/master/docs/sessions.md
Sets up the application pipeline to use cookies for session storage. Requires a secret key for encryption and accepts parameters like expiration time and security flags.
```python
from emmett import App, session
from emmett.sessions import SessionManager
app = App(__name__)
app.pipeline = [SessionManager.cookies('myverysecretkey')]
```
--------------------------------
### Low-Level Cache API: Async Get or Set
Source: https://github.com/emmett-framework/emmett/blob/master/docs/caching.md
Provides `get_or_set` behavior for awaitable functions and objects using `get_or_set_loop`. Ensure the provided function is awaitable.
```python
async def somefunction():
return 'value'
value = await cache.get_or_set_loop('key', somefunction, duration=300)
```
--------------------------------
### Low-Level Cache API: Get or Set
Source: https://github.com/emmett-framework/emmett/blob/master/docs/caching.md
A compact method to retrieve a value from the cache or set it if it doesn't exist. Invoke callable objects yourself before passing their results.
```python
value = cache.get_or_set('key', 'somevalue', duration=300)
```
--------------------------------
### Low-Level Cache API: Manual Check-and-Set
Source: https://github.com/emmett-framework/emmett/blob/master/docs/caching.md
Implement a manual cache check-and-set policy by first attempting to `get` a value and then using `set` if it's not found.
```python
value = cache.get('key')
if not value:
value = 'somevalue'
cache.set('key', value, duration=300)
```
--------------------------------
### Sum records with aggregation
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/operations.md
Similar to counting, the `sum()` method on a field can be used for aggregation, for example, to sum participants for events in a specific year, grouped by location.
```python
summed = Event.participants.sum()
db(Event.happens_at.year() == 1955).select(
Event.location,
summed,
orderby=Event.location,
groupby=Event.location)
```
--------------------------------
### Custom Pipeline with ApiKeyPipe
Source: https://context7.com/emmett-framework/emmett/llms.txt
Implement custom request handling logic using Pipe classes. This example shows an API key check that can short-circuit the request.
```python
from emmett import App, Pipe, request, abort
from emmett.sessions import SessionManager
app = App(__name__)
# Custom auth pipe using the pipe() method to short-circuit
class ApiKeyPipe(Pipe):
async def pipe(self, next_pipe, **kwargs):
if request.headers.get("x-api-key") == "secret":
return await next_pipe(**kwargs)
return {"error": "Unauthorized"}
```
--------------------------------
### before_save Callback Example
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/callbacks.md
The `before_save` callback is executed just before a record is saved. The decorated method receives the record that is about to be saved. This callback is invoked before `before_insert` or `before_update` callbacks.
```python
class Product(Model):
name = Field.string()
price = Field.float(default=0.0)
class CartElement(Model):
belongs_to("product")
quantity = Field.int(default=1)
price_denorm = Field.float(default=0.0)
@before_save
def _rebuild_price(self, row):
row.price_denorm = row.quantity * row.product.price
```
--------------------------------
### Applying DBPipe Globally
Source: https://github.com/emmett-framework/emmett/blob/master/docs/pipeline.md
Shows how to set a pipeline globally for all routes in the application by assigning it to app.pipeline.
```python
app.pipeline = [DBPipe(db)]
```
--------------------------------
### Low-Level Cache API Operations
Source: https://context7.com/emmett-framework/emmett/llms.txt
Interact with the cache using low-level methods like `set`, `get`, `get_or_set`, and `clear`. These provide direct control over cache entries.
```python
from emmett import App
from emmett.cache import Cache, RamCache, RedisCache
app = App(__name__)
cache = Cache(
ram=RamCache(default_expire=60),
redis=RedisCache(host="localhost", port=6379, default_expire=300),
default="ram",
)
# 5. Low-level API
cache.set("key", "value", duration=300)
value = cache.get("key") # None if expired
value = cache.get_or_set("key", "fallback", 300)
value = await cache.get_or_set_loop("key", fetch_async, 30)
cache.clear("key") # specific key; cache.clear() clears all
```
--------------------------------
### Invoking a Virtual Method
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/virtuals.md
Shows how to call a virtual method ('total') on a selected row to get its computed value. Unlike virtual attributes, methods require invocation.
```python
>>> item = db(db.Item.price > 2).select().first()
>>> item.total()
30.0
```
--------------------------------
### File Upload Handling with Request Object
Source: https://context7.com/emmett-framework/emmett/llms.txt
Shows how to handle file uploads using `request.files` and save them to disk.
```python
@app.route("/upload", methods=["post"])
async def upload():
files = await request.files
f = files.document
# Save to disk preserving original filename
await f.save(f"uploads/{f.filename}")
return {"filename": f.filename, "size": f.size, "type": f.content_type}
```
--------------------------------
### after_save Callback Example
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/callbacks.md
The `after_save` callback is triggered immediately after a record has been saved. The decorated method receives the saved record. This callback is invoked after `after_insert` or `after_update` callbacks.
```python
class User(Model):
email = Field()
@after_save
def _send_welcome_email(self, row):
# if is a new user, send a welcome email
if row.has_changed_value("id"):
send_welcome_email(row.email)
```
--------------------------------
### Create URL Valid Strings with urlify
Source: https://github.com/emmett-framework/emmett/blob/master/docs/validations.md
Use the 'urlify' helper to create URL-valid strings. Set 'underscore' to True to keep underscores.
```python
urldata = Field(validation={'urlify': True})
```
```python
urldata = Field(validation={'urlify': {'underscore': True}})
```
--------------------------------
### Configure Auth Module
Source: https://github.com/emmett-framework/emmett/blob/master/docs/tutorial.md
Set single template, disable registration verification, and define HMAC key for password encryption.
```python
app.config.auth.single_template = True
app.config.auth.registration_verification = False
app.config.auth.hmac_key = "november.5.1955"
```
--------------------------------
### Configure Application Settings
Source: https://github.com/emmett-framework/emmett/blob/master/docs/app_and_modules.md
Use the App.config object to set application-wide configurations. Sub-namespaces are automatically created, simplifying configuration management.
```python
from emmett import App
app = App(__name__)
app.config.foo = "bar"
app.config.db.adapter = "mysql"
app.config.db.host = "127.0.0.1"
app.config.Haml.set_as_default = True
```
--------------------------------
### Define a Scope with Arguments
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/scopes.md
Scopes can accept arguments, making them useful for building queries with variables. This example defines a scope to filter posts within a date range.
```python
class Post(Model):
@scope('between')
def filter_between(self, start, end):
return (self.created_at >= start) & (self.created_at < end)
```
--------------------------------
### Enable Static File Versioning
Source: https://github.com/emmett-framework/emmett/blob/master/docs/routing.md
Configure static file versioning by setting `static_version_urls` to True and providing a `static_version` string. This automatically prefixes static file URLs with the version.
```python
app.config.static_version_urls = True
app.config.static_version = "1.0.0"
```
--------------------------------
### Create Download Route for Uploaded Files
Source: https://github.com/emmett-framework/emmett/blob/master/docs/forms.md
Creates a route to serve uploaded files. This is necessary to display or access files uploaded via forms.
```python
from emmett import response
@app.route("/download/")
async def download(filename):
return response.wrap_dbfile(db, filename)
```
--------------------------------
### Limit Results by Offset and Count
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/operations.md
Use the `limitby` option with a tuple to specify the starting offset and the ending offset for limiting results, similar to SQL's `LIMIT BY`.
```python
Event.all().select(limitby=(25, 50))
```
--------------------------------
### Empty Migration Template
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/migrations.md
A template for a new migration file where the 'up' and 'down' methods are intentionally left empty. This serves as a starting point for custom migration logic.
```python
from emmett.orm import migrations
class Migration(migrations.Migration):
revision = '57f23e051fa3'
revises = '4dee31071bf8'
def up(self):
pass
def down(self):
pass
```
--------------------------------
### Create an XML Service Pipe
Source: https://github.com/emmett-framework/emmett/blob/master/docs/services.md
Instantiate `ServicePipe` with 'xml' to configure a pipeline for exposing functions as XML services.
```python
from emmett.tools import ServicePipe
# providing an XML service pipe
ServicePipe('xml')
```
--------------------------------
### Fetching a Single Record with `first()`
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/operations.md
Shows how to efficiently fetch a single record using `select().first()`, handling cases where the record might not be found.
```python
event = db(Event.name == "Secret Party").select().first()
if event:
print(
"Event %s starts at %s" % (
event.name,
str(event.happens_at)
)
)
else:
print("Event not found")
```
--------------------------------
### Update a record using Row.update_record
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/operations.md
Fetch a specific record using `get()` and then update it using the `update_record()` method on the `Row` object. This method returns the updated `Row` object.
```python
>>> row = Event.get(1)
>>> row.update_record(participants=3)
```
--------------------------------
### Create Table
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/migrations.md
Use `create_table` to define a new table with specified columns. The first column should always be 'id' of type 'id'.
```python
self.create_table(
'tags',
migrations.Column('id', 'id'),
migrations.Column('name', 'string', length=512))
```
--------------------------------
### SessionManager Configuration
Source: https://context7.com/emmett-framework/emmett/llms.txt
Shows how to configure and enable session management in the Emmett framework using `SessionManager`. Examples include cookie-based sessions with various options and a placeholder for filesystem-based sessions.
```APIDOC
## Sessions
`SessionManager` pipes store and retrieve per-client sessions via cookies, filesystem, or Redis. Add to `app.pipeline` to enable the `session` object in all routes.
```python
from emmett import App, session
from emmett.sessions import SessionManager
from redis import Redis
app = App(__name__)
# --- Cookie-based (data encrypted in cookie) ---
app.pipeline = [SessionManager.cookies(
"mysecretkey",
expire=3600,
secure=False,
samesite="Lax",
)]
# --- Filesystem-based ---
```
--------------------------------
### Configure Basic Mailer
Source: https://github.com/emmett-framework/emmett/blob/master/docs/mailer.md
Initialize the Mailer with your application and set the default sender address. This configuration uses the local machine as the SMTP server.
```python
from emmett import App
from emmett.tools import Mailer
app = App(__name__)
app.config.mailer.sender = "nina@massivedynamic.com"
mailer = Mailer(app)
```
--------------------------------
### Field Validation with Presence Rule
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/models.md
Define field validation rules directly within the Field constructor using a dictionary. This example shows how to enforce the presence of a 'title' field.
```python
title = Field(validation={'presence': True})
```
--------------------------------
### Initialize Default Cache
Source: https://github.com/emmett-framework/emmett/blob/master/docs/caching.md
Instantiate the Cache class to use the default RAM cache handler.
```python
from emmett.cache import Cache
cache = Cache()
```
--------------------------------
### Extension Defining a Route
Source: https://github.com/emmett-framework/emmett/blob/master/docs/extensions.md
Illustrates how an extension can interact with the application instance to define routes. The `on_load` method is used to register the route.
```python
class Awesomeness(Extension):
def on_load(self):
self.app.route('/awesome')(awesome_route)
async def awesome_route():
return {'message': 'Awesome!'}
```
--------------------------------
### Add Custom Auth Route
Source: https://github.com/emmett-framework/emmett/blob/master/docs/auth.md
Define and register custom authentication routes within the auth module. This example shows how to route a Facebook authentication method to the '/account/facebook' path.
```python
@auth_routes.route("/facebook")
def facebook_auth():
# some code
```
--------------------------------
### Initialize Disk Cache
Source: https://github.com/emmett-framework/emmett/blob/master/docs/caching.md
Configure the Cache class to use the DiskCache handler for persistent storage. DiskCache accepts cache_dir, threshold, and default_expire parameters.
```python
from emmett.cache import Cache, DiskCache
cache = Cache(disk=DiskCache())
```
--------------------------------
### Define a Command Group and Nested Command
Source: https://github.com/emmett-framework/emmett/blob/master/docs/cli.md
Organize related commands into logical groups using the @app.command_group decorator. This example creates a 'tasks' group with a nested 'create' command.
```python
@app.command_group('tasks')
def tasks_cmd():
pass
@tasks_cmd.command('create')
def tasks_create_cmd():
# some code here
```
--------------------------------
### Enable Modern Session Encryption
Source: https://github.com/emmett-framework/emmett/blob/master/docs/upgrading.md
To upgrade to the modern session encryption algorithm, install the crypto extras and set the encryption_mode to 'modern' in the SessionManager.cookies constructor. This change will invalidate all active sessions.
```python
SessionManager.cookies('myverysecretkey', encryption_mode='modern')
```
--------------------------------
### Create City Record with Geo Point
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/operations.md
Demonstrates creating a new record using the geo.Point helper for a geography field.
```python
from emmett.orm import geo
rv = City.create(
name="Hill Valley",
location=geo.Point(44, 12)
)
```
--------------------------------
### Access Related Data with belongs_to
Source: https://github.com/emmett-framework/emmett/blob/master/docs/orm/relations.md
After defining a `belongs_to` relation, related records can be accessed as attributes on the model instance. This example shows accessing a doctor's name from a patient object.
```python
patient = db.Patient(name="Pinkman")
doctor_name = patient.doctor.name
```