Compare commits
9 Commits
main
...
guide-impr
Author | SHA1 | Date | |
---|---|---|---|
|
8ad0a153c5 | ||
|
86a414fd58 | ||
|
5a7ed4d4fe | ||
|
81d986a413 | ||
|
f613818263 | ||
|
36ea283b42 | ||
|
a7766de797 | ||
|
b67e31efe8 | ||
|
7ac4933386 |
|
@ -1,10 +1,12 @@
|
|||
# Sanic Application
|
||||
|
||||
See API docs: [sanic.app](/api/sanic.app)
|
||||
|
||||
## Instance
|
||||
|
||||
.. column::
|
||||
|
||||
The most basic building block is the `Sanic()` instance. It is not required, but the custom is to instantiate this in a file called `server.py`.
|
||||
The most basic building block is the :class:`sanic.app.Sanic` instance. It is not required, but the custom is to instantiate this in a file called `server.py`.
|
||||
|
||||
.. column::
|
||||
|
||||
|
@ -18,33 +20,36 @@
|
|||
|
||||
## Application context
|
||||
|
||||
Most applications will have the need to share/reuse data or objects across different parts of the code base. The most common example is DB connections.
|
||||
Most applications will have the need to share/reuse data or objects across different parts of the code base. Sanic helps be providing the `ctx` object on application instances. It is a free space for the developer to attach any objects or data that should existe throughout the lifetime of the application.
|
||||
|
||||
|
||||
.. column::
|
||||
|
||||
In versions of Sanic prior to v21.3, this was commonly done by attaching an attribute to the application instance
|
||||
The most common pattern is to attach a database instance to the application.
|
||||
|
||||
.. column::
|
||||
|
||||
```python
|
||||
# Raises a warning as deprecated feature in 21.3
|
||||
app = Sanic("MyApp")
|
||||
app.db = Database()
|
||||
```
|
||||
|
||||
|
||||
.. column::
|
||||
|
||||
Because this can create potential problems with name conflicts, and to be consistent with [request context](./request.md#context) objects, v21.3 introduces application level context object.
|
||||
|
||||
.. column::
|
||||
|
||||
```python
|
||||
# Correct way to attach objects to the application
|
||||
app = Sanic("MyApp")
|
||||
app.ctx.db = Database()
|
||||
```
|
||||
|
||||
|
||||
.. column::
|
||||
|
||||
While the previous example will work and is illustrative, it is typically considered best practice to attach objects in one of the two application startup [listeners](./listeners).
|
||||
|
||||
.. column::
|
||||
|
||||
```python
|
||||
app = Sanic("MyApp")
|
||||
|
||||
@app.before_server_start
|
||||
async def attach_db(app, loop):
|
||||
app.ctx.db = Database()
|
||||
```
|
||||
|
||||
|
||||
## App Registry
|
||||
|
||||
.. column::
|
||||
|
@ -68,7 +73,7 @@ Most applications will have the need to share/reuse data or objects across diffe
|
|||
|
||||
.. column::
|
||||
|
||||
If you call `Sanic.get_app("non-existing")` on an app that does not exist, it will raise `SanicException` by default. You can, instead, force the method to return a new instance of Sanic with that name.
|
||||
If you call `Sanic.get_app("non-existing")` on an app that does not exist, it will raise :class:`sanic.exceptions.SanicException` by default. You can, instead, force the method to return a new instance of Sanic with that name.
|
||||
|
||||
.. column::
|
||||
|
||||
|
@ -119,25 +124,62 @@ Most applications will have the need to share/reuse data or objects across diffe
|
|||
.. note:: Heads up
|
||||
|
||||
Config keys _should_ be uppercase. But, this is mainly by convention, and lowercase will work most of the time.
|
||||
```
|
||||
```python
|
||||
app.config.GOOD = "yay!"
|
||||
app.config.bad = "boo"
|
||||
```
|
||||
|
||||
|
||||
There is much [more detail about configuration](/guide/deployment/configuration.md) later on.
|
||||
There is much [more detail about configuration](../running/configuration.md) later on.
|
||||
|
||||
## Factory pattern
|
||||
|
||||
Many of the examples in these docs will show the instantiation of the :class:`sanic.app.Sanic` instance in a file called `server.py` in the "global scope" (i.e. not inside a function). This is a common pattern for very simple "hello world" style applications, but it is often beneficial to use a factory pattern instead.
|
||||
|
||||
A "factory" is just a function that returns an instance of the object you want to use. This allows you to abstract the instantiation of the object, but also may make it easier to isolate the application instance.
|
||||
|
||||
.. column::
|
||||
|
||||
A super simple factory pattern could look like this:
|
||||
|
||||
.. column::
|
||||
|
||||
```python
|
||||
# ./path/to/server.py
|
||||
from sanic import Sanic
|
||||
from .path.to.config import MyConfig
|
||||
from .path.to.some.blueprint import bp
|
||||
|
||||
|
||||
def create_app(config=MyConfig) -> Sanic:
|
||||
app = Sanic("MyApp", config=config)
|
||||
app.blueprint(bp)
|
||||
return app
|
||||
```
|
||||
|
||||
.. column::
|
||||
|
||||
When we get to running Sanic later, you will learn that the Sanic CLI can detect this pattern and use it to run your application.
|
||||
|
||||
.. column::
|
||||
|
||||
```sh
|
||||
sanic path.to.server:create_app
|
||||
```
|
||||
|
||||
## Customization
|
||||
|
||||
The Sanic application instance can be customized for your application needs in a variety of ways at instantiation.
|
||||
|
||||
For complete details, see the [API docs](/api/sanic.app).
|
||||
|
||||
### Custom configuration
|
||||
|
||||
.. column::
|
||||
|
||||
This simplest form of custom configuration would be to pass your own object directly into that Sanic application instance
|
||||
|
||||
If you create a custom configuration object, it is *highly* recommended that you subclass the Sanic `Config` option to inherit its behavior. You could use this option for adding properties, or your own set of custom logic.
|
||||
If you create a custom configuration object, it is *highly* recommended that you subclass the :class:`sanic.config.Config` option to inherit its behavior. You could use this option for adding properties, or your own set of custom logic.
|
||||
|
||||
*Added in v21.6*
|
||||
|
||||
|
@ -293,7 +335,7 @@ The Sanic application instance can be customized for your application needs in a
|
|||
```python
|
||||
from orjson import dumps
|
||||
|
||||
app = Sanic(__name__, dumps=dumps)
|
||||
app = Sanic("MyApp", dumps=dumps)
|
||||
```
|
||||
|
||||
### Custom loads function
|
||||
|
@ -309,7 +351,7 @@ The Sanic application instance can be customized for your application needs in a
|
|||
```python
|
||||
from orjson import loads
|
||||
|
||||
app = Sanic(__name__, loads=loads)
|
||||
app = Sanic("MyApp", loads=loads)
|
||||
```
|
||||
|
||||
|
||||
|
@ -318,7 +360,7 @@ The Sanic application instance can be customized for your application needs in a
|
|||
|
||||
### Custom typed application
|
||||
|
||||
The correct, default type of a Sanic application instance is:
|
||||
Beginnint in v23.6, the correct type annotation of a default Sanic application instance is:
|
||||
|
||||
```python
|
||||
sanic.app.Sanic[sanic.config.Config, types.SimpleNamespace]
|
||||
|
@ -326,14 +368,14 @@ sanic.app.Sanic[sanic.config.Config, types.SimpleNamespace]
|
|||
|
||||
It refers to two generic types:
|
||||
|
||||
1. The first is the type of the configuration object. It defaults to `sanic.config.Config`, but can be any subclass of that.
|
||||
2. The second is the type of the application context. It defaults to `types.SimpleNamespace`, but can be **any object** as show above.
|
||||
1. The first is the type of the configuration object. It defaults to :class:`sanic.config.Config`, but can be any subclass of that.
|
||||
2. The second is the type of the application context. It defaults to [`SimpleNamespace()`](https://docs.python.org/3/library/types.html#types.SimpleNamespace), but can be **any object** as show above.
|
||||
|
||||
Let's look at some examples of how the type will change.
|
||||
|
||||
.. column::
|
||||
|
||||
Consider this example where we pass a custom subclass of `Config` and a custom context object.
|
||||
Consider this example where we pass a custom subclass of :class:`sanic.config.Config` and a custom context object.
|
||||
|
||||
.. column::
|
||||
|
||||
|
@ -431,7 +473,9 @@ add_listeners(app)
|
|||
|
||||
*Added in v23.6*
|
||||
|
||||
### Custom typed request
|
||||
.. new:: NEW in v23.6
|
||||
|
||||
### Custom typed request
|
||||
|
||||
Sanic also allows you to customize the type of the request object. This is useful if you want to add custom properties to the request object, or be able to access your custom properties of a typed application instance.
|
||||
|
||||
|
@ -511,7 +555,7 @@ Let's look at some examples of how the type will change.
|
|||
pass
|
||||
```
|
||||
|
||||
See more information in the [custom request context](./request.md#custom-request-context) section.
|
||||
See more information in the [custom request context](./request#custom-request-context) section.
|
||||
|
||||
*Added in v23.6*
|
||||
|
||||
|
|
|
@ -2,9 +2,7 @@
|
|||
|
||||
The next important building block are your _handlers_. These are also sometimes called "views".
|
||||
|
||||
In Sanic, a handler is any callable that takes at least a `Request` instance as an argument, and returns either an `HTTPResponse` instance, or a coroutine that does the same.
|
||||
|
||||
|
||||
In Sanic, a handler is any callable that takes at least a :class:`sanic.request.Request` instance as an argument, and returns either an :class:`sanic.response.HTTPResponse` instance, or a coroutine that does the same.
|
||||
|
||||
.. column::
|
||||
|
||||
|
@ -24,26 +22,39 @@ In Sanic, a handler is any callable that takes at least a `Request` instance as
|
|||
return HTTPResponse()
|
||||
```
|
||||
|
||||
Two more important items to note:
|
||||
|
||||
1. You almost *never* will want to use :class:`sanic.response.HTTPresponse` directly. It is much simpler to use one of the [convenience methods](./response#methods).
|
||||
|
||||
- `from sanic import json`
|
||||
- `from sanic import html`
|
||||
- `from sanic import redirect`
|
||||
- *etc*
|
||||
|
||||
1. As we will see in [the streaming section](../advanced/streaming#response-streaming), you do not always need to return an object. If you use this lower-level API, you can control the flow of the response from within the handler, and a return object is not used.
|
||||
|
||||
.. tip:: Heads up
|
||||
|
||||
If you want to learn more about encapsulating your logic, checkout [class based views](/guide/advanced/class-based-views.md).
|
||||
If you want to learn more about encapsulating your logic, checkout [class based views](../advanced/class-based-views.md). For now, we will continue forward with just function-based views.
|
||||
|
||||
|
||||
### A simple function-based handler
|
||||
|
||||
The most common way to create a route handler is to decorate the function. It creates a visually simple identification of a route definition. We'll learn more about [routing soon](./routing.md).
|
||||
|
||||
.. column::
|
||||
|
||||
Then, all you need to do is wire it up to an endpoint. We'll learn more about [routing soon](./routing.md).
|
||||
|
||||
Let's look at a practical example.
|
||||
|
||||
- We use a convenience decorator on our app instance: `@app.get()`
|
||||
- And a handy convenience method for generating out response object: `text()`
|
||||
|
||||
Mission accomplished :muscle:
|
||||
Mission accomplished 💪
|
||||
|
||||
.. column::
|
||||
|
||||
```python
|
||||
from sanic.response import text
|
||||
from sanic import text
|
||||
|
||||
@app.get("/foo")
|
||||
async def foo_handler(request):
|
||||
|
@ -85,16 +96,10 @@ In Sanic, a handler is any callable that takes at least a `Request` instance as
|
|||
- Or, about **3,843.17** requests/second
|
||||
|
||||
.. attrs::
|
||||
:class: is-size-3
|
||||
:class: is-size-2
|
||||
|
||||
🤯
|
||||
|
||||
Okay... this is a ridiculously overdramatic result. And any benchmark you see is inherently very biased. This example is meant to over-the-top show the benefit of `async/await` in the web world. Results will certainly vary. Tools like Sanic and other async Python libraries are not magic bullets that make things faster. They make them _more efficient_.
|
||||
|
||||
In our example, the asynchronous version is so much better because while one request is sleeping, it is able to start another one, and another one, and another one, and another one...
|
||||
|
||||
But, this is the point! Sanic is fast because it takes the available resources and squeezes performance out of them. It can handle many requests concurrently, which means more requests per second.
|
||||
|
||||
.. column::
|
||||
|
||||
```python
|
||||
|
@ -105,14 +110,20 @@ In Sanic, a handler is any callable that takes at least a `Request` instance as
|
|||
```
|
||||
|
||||
|
||||
Okay... this is a ridiculously overdramatic result. And any benchmark you see is inherently very biased. This example is meant to over-the-top show the benefit of `async/await` in the web world. Results will certainly vary. Tools like Sanic and other async Python libraries are not magic bullets that make things faster. They make them _more efficient_.
|
||||
|
||||
.. warning:: A common mistake!
|
||||
In our example, the asynchronous version is so much better because while one request is sleeping, it is able to start another one, and another one, and another one, and another one...
|
||||
|
||||
But, this is the point! Sanic is fast because it takes the available resources and squeezes performance out of them. It can handle many requests concurrently, which means more requests per second.
|
||||
|
||||
|
||||
.. tip:: A common mistake!
|
||||
|
||||
Don't do this! You need to ping a website. What do you use? `pip install your-fav-request-library` 🙈
|
||||
|
||||
Instead, try using a client that is `async/await` capable. Your server will thank you. Avoid using blocking tools, and favor those that play well in the asynchronous ecosystem. If you need recommendations, check out [Awesome Sanic](https://github.com/mekicha/awesome-sanic).
|
||||
|
||||
Sanic uses [httpx](https://www.python-httpx.org/) inside of its testing package (sanic-testing) :wink:.
|
||||
Sanic uses [httpx](https://www.python-httpx.org/) inside of its testing package (sanic-testing) 😉.
|
||||
|
||||
|
||||
---
|
||||
|
@ -129,3 +140,52 @@ from sanic.request import Request
|
|||
async def typed_handler(request: Request) -> HTTPResponse:
|
||||
return text("Done.")
|
||||
```
|
||||
|
||||
## Naming your handlers
|
||||
|
||||
All handlers are named automatically. This is useful for debugging, and for generating URLs in templates. When not specified, the name that will be used is the name of the function.
|
||||
|
||||
.. column::
|
||||
|
||||
For example, this handler will be named `foo_handler`.
|
||||
|
||||
.. column::
|
||||
|
||||
```python
|
||||
# Handler name will be "foo_handler"
|
||||
@app.get("/foo")
|
||||
async def foo_handler(request):
|
||||
return text("I said foo!")
|
||||
```
|
||||
|
||||
.. column::
|
||||
|
||||
However, you can override this by passing the `name` argument to the decorator.
|
||||
|
||||
.. column::
|
||||
|
||||
```python
|
||||
# Handler name will be "foo"
|
||||
@app.get("/foo", name="foo")
|
||||
async def foo_handler(request):
|
||||
return text("I said foo!")
|
||||
```
|
||||
|
||||
.. column::
|
||||
|
||||
In fact, as you will, there may be times when you **MUST** supply a name. For example, if you use two decorators on the same function, you will need to supply a name for at least one of them.
|
||||
|
||||
If you do not, you will get an error and your app will not start. Names **must** be unique within your app.
|
||||
|
||||
.. column::
|
||||
|
||||
```python
|
||||
# Two handlers, same function,
|
||||
# different names:
|
||||
# - "foo"
|
||||
# - "foo_handler"
|
||||
@app.get("/foo", name="foo")
|
||||
@app.get("/bar")
|
||||
async def foo_handler(request):
|
||||
return text("I said foo!")
|
||||
```
|
||||
|
|
|
@ -1,6 +1,49 @@
|
|||
# Request
|
||||
|
||||
The `Request` instance contains **a lot** of helpful information available on its parameters. Refer to the [API documentation](https://sanic.readthedocs.io/) for full details.
|
||||
See API docs: [sanic.request](/api/sanic.request)
|
||||
|
||||
The :class:`sanic.request.Request` instance contains **a lot** of helpful information available on its parameters. Refer to the [API documentation](https://sanic.readthedocs.io/) for full details.
|
||||
|
||||
As we saw in the section on [handlers](./handlers), the first argument in a route handler is usually the :class:`sanic.request.Request` object. Because Sanic is an async framework, the handler will run inside of a [`asyncio.Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task) and will be scheduled by the event loop. This means that the handler will be executed in an isolated context and the request object will be unique to that handler's task.
|
||||
|
||||
.. column::
|
||||
|
||||
By convention, the argument is named `request`, but you can name it whatever you want. The name of the argument is not important. Both of the following handlers are valid.
|
||||
|
||||
.. column::
|
||||
|
||||
```python
|
||||
@app.get("/foo")
|
||||
async def typical_use_case(request):
|
||||
return text("I said foo!")
|
||||
```
|
||||
|
||||
```python
|
||||
@app.get("/foo")
|
||||
async def atypical_use_case(req):
|
||||
return text("I said foo!")
|
||||
```
|
||||
|
||||
.. column::
|
||||
|
||||
Annotating a request object is super simple.
|
||||
|
||||
.. column::
|
||||
|
||||
```python
|
||||
from sanic.request import Request
|
||||
from sanic.response import text
|
||||
|
||||
@app.get("/typed")
|
||||
async def typed_handler(request: Request):
|
||||
return text("Done.")
|
||||
```
|
||||
|
||||
.. tip::
|
||||
|
||||
For your convenience, assuming you are using a modern IDE, you should leverage type annotations to help with code completion and documentation. This is especially helpful when using the `request` object as it has **MANY** properties and methods.
|
||||
|
||||
To see the full list of available properties and methods, refer to the [API documentation](/api/sanic.request).
|
||||
|
||||
## Body
|
||||
|
||||
|
@ -112,7 +155,15 @@ The `Request` object allows you to access the content of the request body in a f
|
|||
|
||||
### Request context
|
||||
|
||||
The `request.ctx` object is your playground to store whatever information you need to about the request.
|
||||
The `request.ctx` object is your playground to store whatever information you need to about the request. This lives only for the duration of the request and is unique to the request.
|
||||
|
||||
This can be constrasted with the `app.ctx` object which is shared across all requests. Be careful not to confuse them!
|
||||
|
||||
The `request.ctx` object by default is a `SimpleNamespace` object allowing you to set arbitrary attributes on it. Sanic will not use this object for anything, so you are free to use it however you want without worrying about name clashes.
|
||||
|
||||
```python
|
||||
|
||||
### Typical use case
|
||||
|
||||
This is often used to store items like authenticated user details. We will get more into [middleware](./middleware.md) later, but here is a simple example.
|
||||
|
||||
|
@ -123,12 +174,12 @@ async def run_before_handler(request):
|
|||
|
||||
@app.route('/hi')
|
||||
async def hi_my_name_is(request):
|
||||
return text("Hi, my name is {}".format(request.ctx.user.name))
|
||||
if not request.ctx.user:
|
||||
return text("Hmm... I don't know you)
|
||||
return text(f"Hi, my name is {request.ctx.user.name}")
|
||||
```
|
||||
|
||||
A typical use case would be to store the user object acquired from database in an authentication middleware. Keys added are accessible to all later middleware as well as the handler over the duration of the request.
|
||||
|
||||
Custom context is reserved for applications and extensions. Sanic itself makes no use of it.
|
||||
As you can see, the `request.ctx` object is a great place to store information that you need to access in multiple handlers making your code more DRY and easier to maintain. But, as we will learn in the [middleware section](./middleware.md), you can also use it to store information from one middleware that will be used in another.
|
||||
|
||||
### Connection context
|
||||
|
||||
|
@ -161,9 +212,15 @@ Custom context is reserved for applications and extensions. Sanic itself makes n
|
|||
request.conn_info.ctx.foo=3
|
||||
```
|
||||
|
||||
.. warning::
|
||||
|
||||
While this looks like a convenient place to store information between requests by a single HTTP connection, do not assume that all requests on a single connection came from a single end user. This is because HTTP proxies and load balancers can multiplex multiple connections into a single connection to your server.
|
||||
|
||||
**DO NOT** use this to store information about a single user. Use the `request.ctx` object for that.
|
||||
|
||||
### Custom Request Objects
|
||||
|
||||
As dicussed in [application customization](./app.md#custom-requests), you can create a subclass of `sanic.Request` to add additional functionality to the request object. This is useful for adding additional attributes or methods that are specific to your application.
|
||||
As dicussed in [application customization](./app.md#custom-requests), you can create a subclass of :class:`sanic.request.Request` to add additional functionality to the request object. This is useful for adding additional attributes or methods that are specific to your application.
|
||||
|
||||
.. column::
|
||||
|
||||
|
@ -201,13 +258,13 @@ As dicussed in [application customization](./app.md#custom-requests), you can cr
|
|||
|
||||
### Custom Request Context
|
||||
|
||||
By default, the request context (`request.ctx`) is a `SimpleNamespace` object allowing you to set arbitrary attributes on it. While this is super helpful to reuse logic across your application, it can be difficult in the development experience since the IDE will not know what attributes are available.
|
||||
By default, the request context (`request.ctx`) is a [`Simplenamespace`](https://docs.python.org/3/library/types.html#types.SimpleNamespace) object allowing you to set arbitrary attributes on it. While this is super helpful to reuse logic across your application, it can be difficult in the development experience since the IDE will not know what attributes are available.
|
||||
|
||||
To help with this, you can create a custom request context object that will be used instead of the default `SimpleNamespace`. This allows you to add type hints to the context object and have them be available in your IDE.
|
||||
|
||||
.. column::
|
||||
|
||||
Start by subclassing the `sanic.Request` class to create a custom request type. Then, you will need to add a `make_context()` method that returns an instance of your custom context object. *NOTE: the `make_context` method should be a static method.*
|
||||
Start by subclassing the :class:`sanic.request.Request` class to create a custom request type. Then, you will need to add a `make_context()` method that returns an instance of your custom context object. *NOTE: the `make_context` method should be a static method.*
|
||||
|
||||
.. column::
|
||||
|
||||
|
@ -229,6 +286,10 @@ To help with this, you can create a custom request context object that will be u
|
|||
user_id: str = None
|
||||
```
|
||||
|
||||
.. note::
|
||||
|
||||
This is a Sanic poweruser feature that makes it super convenient in large codebases to have typed request context objects. It is of course not required, but can be very helpful.
|
||||
|
||||
*Added in v23.6*
|
||||
|
||||
|
||||
|
@ -236,7 +297,7 @@ To help with this, you can create a custom request context object that will be u
|
|||
|
||||
.. column::
|
||||
|
||||
Values that are extracted from the path are injected into the handler as parameters, or more specifically as keyword arguments. There is much more detail about this in the [Routing section](./routing.md).
|
||||
Values that are extracted from the path parameters are injected into the handler as argumets, or more specifically as keyword arguments. There is much more detail about this in the [Routing section](./routing.md).
|
||||
|
||||
.. column::
|
||||
|
||||
|
@ -244,6 +305,11 @@ To help with this, you can create a custom request context object that will be u
|
|||
@app.route('/tag/<tag>')
|
||||
async def tag_handler(request, tag):
|
||||
return text("Tag - {}".format(tag))
|
||||
|
||||
# or, explicitly as keyword arguments
|
||||
@app.route('/tag/<tag>')
|
||||
async def tag_handler(request, *, tag):
|
||||
return text("Tag - {}".format(tag))
|
||||
```
|
||||
|
||||
|
||||
|
@ -254,8 +320,43 @@ There are two attributes on the `request` instance to get query parameters:
|
|||
- `request.args`
|
||||
- `request.query_args`
|
||||
|
||||
```bash
|
||||
$ curl http://localhost:8000\?key1\=val1\&key2\=val2\&key1\=val3
|
||||
These allow you to access the query parameters from the request path (the part after the `?` in the URL).
|
||||
|
||||
### Typical use case
|
||||
|
||||
In most use cases, you will want to use the `request.args` object to access the query parameters. This will be the parsed query string as a dictionary.
|
||||
|
||||
This is by far the most common pattern.
|
||||
|
||||
.. column::
|
||||
|
||||
Consider the example where we have a `/search` endpoint with a `q` parameter that we want to use to search for something.
|
||||
|
||||
.. column::
|
||||
|
||||
```python
|
||||
@app.get("/search")
|
||||
async def search(request):
|
||||
query = request.args.get("q")
|
||||
if not query:
|
||||
return text("No query string provided")
|
||||
return text(f"Searching for: {query}")
|
||||
```
|
||||
|
||||
### Parsing the query string
|
||||
|
||||
Sometimes, however, you may want to access the query string as a raw string or as a list of tuples. For this, you can use the `request.query_string` and `request.query_args` attributes.
|
||||
|
||||
It also should be noted that HTTP allows multiple values for a single key. Although `request.args` may seem like a regular dictionary, it is actually a special type that allows for multiple values for a single key. You can access this by using the `request.args.getlist()` method.
|
||||
|
||||
- `request.query_string` - The raw query string
|
||||
- `request.query_args` - The parsed query string as a list of tuples
|
||||
- `request.args` - The parsed query string as a *special* dictionary
|
||||
- `request.args.get()` - Get the first value for a key (behaves like a regular dictionary)
|
||||
- `request.args.getlist()` - Get all values for a key
|
||||
|
||||
```sh
|
||||
curl "http://localhost:8000?key1=val1&key2=val2&key1=val3"
|
||||
```
|
||||
|
||||
```python
|
||||
|
@ -283,11 +384,12 @@ key1=val1&key2=val2&key1=val3
|
|||
|
||||
Most of the time you will want to use the `.get()` method to access the first element and not a list. If you do want a list of all items, you can use `.getlist()`.
|
||||
|
||||
|
||||
## Current request getter
|
||||
|
||||
Sometimes you may find that you need access to the current request in your application in a location where it is not accessible. A typical example might be in a `logging` format. You can use `Request.get_current()` to fetch the current request (if any).
|
||||
|
||||
Remember, the request object is confined to the single [`asyncio.Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task) that is running the handler. If you are not in that task, there is no request object.
|
||||
|
||||
```python
|
||||
import logging
|
||||
|
||||
|
@ -317,8 +419,8 @@ def record_factory(*args, **kwargs):
|
|||
|
||||
logging.setLogRecordFactory(record_factory)
|
||||
|
||||
LOGGING_CONFIG_DEFAULTS["formatters"]["access"]["format"] = LOGGING_FORMAT
|
||||
|
||||
LOGGING_CONFIG_DEFAULTS["formatters"]["access"]["format"] = LOGGING_FORMAT
|
||||
app = Sanic("Example", log_config=LOGGING_CONFIG_DEFAULTS)
|
||||
```
|
||||
|
||||
|
|
|
@ -2,6 +2,9 @@ let burger;
|
|||
let menu;
|
||||
let menuLinks;
|
||||
let menuGroups;
|
||||
let anchors;
|
||||
let lastUpdated = 0;
|
||||
let updateFrequency = 300;
|
||||
function trigger(el, eventType) {
|
||||
if (typeof eventType === "string" && typeof el[eventType] === "function") {
|
||||
el[eventType]();
|
||||
|
@ -44,6 +47,30 @@ function hasActiveLink(element) {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
function scrollHandler(e) {
|
||||
let now = Date.now();
|
||||
if (now - lastUpdated < updateFrequency) return;
|
||||
|
||||
let closestAnchor = null;
|
||||
let closestDistance = Infinity;
|
||||
|
||||
if (!anchors) { return; }
|
||||
|
||||
anchors.forEach(anchor => {
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
const distance = Math.abs(rect.top);
|
||||
|
||||
if (distance < closestDistance) {
|
||||
closestDistance = distance;
|
||||
closestAnchor = anchor;
|
||||
}
|
||||
});
|
||||
|
||||
if (closestAnchor) {
|
||||
history.replaceState(null, null, "#" + closestAnchor.id);
|
||||
lastUpdated = now;
|
||||
}
|
||||
}
|
||||
function initBurger() {
|
||||
if (!burger || !menu) {
|
||||
return;
|
||||
|
@ -110,6 +137,10 @@ function initSearch() {
|
|||
);
|
||||
});
|
||||
}
|
||||
function refreshAnchors() {
|
||||
anchors = document.querySelectorAll("h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]");
|
||||
};
|
||||
|
||||
function setMenuLinkActive(href) {
|
||||
burger.classList.remove("is-active");
|
||||
menu.classList.remove("is-active");
|
||||
|
@ -149,6 +180,7 @@ function init() {
|
|||
refreshMenu();
|
||||
refreshMenuLinks();
|
||||
refreshMenuGroups();
|
||||
refreshAnchors();
|
||||
initBurger();
|
||||
initMenuGroups();
|
||||
initDetails();
|
||||
|
@ -162,3 +194,4 @@ function afterSwap(e) {
|
|||
}
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
document.body.addEventListener("htmx:afterSwap", afterSwap);
|
||||
document.addEventListener("scroll", scrollHandler);
|
||||
|
|
|
@ -272,7 +272,7 @@ th {
|
|||
|
||||
html {
|
||||
background-color: white;
|
||||
font-size: 18px;
|
||||
font-size: 24px;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
min-width: 300px;
|
||||
|
@ -12652,12 +12652,14 @@ a.has-text-danger-dark:hover, a.has-text-danger-dark:focus {
|
|||
.menu hr {
|
||||
background-color: var(--menu-divider); }
|
||||
.menu .is-anchor {
|
||||
font-size: 0.85em; }
|
||||
font-size: 0.75em; }
|
||||
.menu .is-anchor a::before {
|
||||
content: '# ';
|
||||
color: var(--menu-contrast); }
|
||||
.menu .menu-label {
|
||||
margin-bottom: 1rem; }
|
||||
.menu li.is-group > a {
|
||||
font-size: 0.85rem; }
|
||||
.menu li.is-group > a::after {
|
||||
content: '';
|
||||
position: relative;
|
||||
|
@ -12702,6 +12704,16 @@ a.has-text-danger-dark:hover, a.has-text-danger-dark:focus {
|
|||
.burger {
|
||||
display: block; } }
|
||||
|
||||
.menu-list li ul {
|
||||
margin: 0;
|
||||
padding-left: 0; }
|
||||
|
||||
.menu-list ul li:not(.is-anchor) {
|
||||
margin-left: 0.75em; }
|
||||
|
||||
.menu-list .menu-list li a {
|
||||
font-size: 0.85em; }
|
||||
|
||||
code {
|
||||
color: #4a4a4a; }
|
||||
|
||||
|
@ -12718,6 +12730,12 @@ a[target=_blank]::after {
|
|||
content: "⇗";
|
||||
margin-left: 0.25em; }
|
||||
|
||||
a > code {
|
||||
border-bottom: 1px solid #ff0d68; }
|
||||
a > code:hover {
|
||||
background-color: #ff0d68;
|
||||
color: white; }
|
||||
|
||||
h1 a.anchor,
|
||||
h2 a.anchor,
|
||||
h3 a.anchor,
|
||||
|
@ -12768,6 +12786,10 @@ p + p {
|
|||
article {
|
||||
margin-left: 0; } }
|
||||
|
||||
@media screen and (min-width: 1216px) {
|
||||
.section {
|
||||
padding: 3rem 0rem; } }
|
||||
|
||||
.footer {
|
||||
margin-bottom: 4rem; }
|
||||
.footer a[target=_blank]::after {
|
||||
|
@ -12998,6 +13020,51 @@ h3 + .code-block {
|
|||
.tabs .tab-content {
|
||||
display: none; }
|
||||
|
||||
.table-of-contents {
|
||||
position: fixed;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
z-index: 1000;
|
||||
max-width: 500px;
|
||||
padding: 1rem 2rem;
|
||||
background-color: #fafafa;
|
||||
box-shadow: 0 0 2px rgba(63, 63, 68, 0.5); }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.table-of-contents {
|
||||
background-color: #0a0a0a;
|
||||
box-shadow: 0 0 2px rgba(191, 191, 191, 0.5); } }
|
||||
.table-of-contents .table-of-contents-item {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
text-decoration: none; }
|
||||
.table-of-contents .table-of-contents-item:hover {
|
||||
text-decoration: underline;
|
||||
color: #ff0d68; }
|
||||
.table-of-contents .table-of-contents-item:hover strong, .table-of-contents .table-of-contents-item:hover small {
|
||||
color: #ff0d68; }
|
||||
.table-of-contents .table-of-contents-item strong {
|
||||
color: #121212;
|
||||
font-size: 1.15em;
|
||||
display: block;
|
||||
line-height: 1rem;
|
||||
margin-top: 0.75rem; }
|
||||
.table-of-contents .table-of-contents-item small {
|
||||
color: #7a7a7a;
|
||||
font-size: 0.85em; }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.table-of-contents .table-of-contents-item strong {
|
||||
color: #dbdbdb; } }
|
||||
@media (max-width: 768px) {
|
||||
.table-of-contents {
|
||||
position: static;
|
||||
max-width: calc(100vw - 2rem); }
|
||||
.table-of-contents .table-of-contents-item {
|
||||
display: flex;
|
||||
flex-direction: row-reverse;
|
||||
justify-content: start; }
|
||||
.table-of-contents .table-of-contents-item strong {
|
||||
display: inline;
|
||||
margin: 0 0 0 0.75rem; } }
|
||||
footer .level,
|
||||
footer .level .level-right,
|
||||
footer .level .level-left {
|
||||
|
|
|
@ -1,3 +1,8 @@
|
|||
sanic>=23.6.*
|
||||
sanic-ext>=23.6.*
|
||||
msgspec
|
||||
python-frontmatter
|
||||
pygments
|
||||
docstring-parser
|
||||
libsass
|
||||
mistune
|
||||
|
|
|
@ -1,3 +1,11 @@
|
|||
"""Sanic User Guide
|
||||
|
||||
https://sanic.dev
|
||||
|
||||
Built using the SHH stack:
|
||||
- Sanic
|
||||
- html5tagger
|
||||
- HTMX"""
|
||||
from pathlib import Path
|
||||
|
||||
from webapp.worker.factory import create_app
|
||||
|
|
|
@ -290,3 +290,68 @@ h3 + .code-block { margin-top: 1rem; }
|
|||
.tabs {
|
||||
.tab-content { display: none; }
|
||||
}
|
||||
|
||||
.table-of-contents {
|
||||
position: fixed;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
z-index: 1000;
|
||||
max-width: 500px;
|
||||
padding: 1rem 2rem;
|
||||
background-color: $white-bis;
|
||||
box-shadow: 0 0 2px rgba(63, 63, 68, 0.5);
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
background-color: $black;
|
||||
box-shadow: 0 0 2px rgba(191, 191, 191, 0.5);
|
||||
|
||||
}
|
||||
|
||||
.table-of-contents-item {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
color: $primary;
|
||||
|
||||
strong, small {
|
||||
color: $primary;
|
||||
}
|
||||
}
|
||||
|
||||
strong {
|
||||
color: $black-bis;
|
||||
font-size: 1.15em;
|
||||
display: block;
|
||||
line-height: 1rem;
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
|
||||
small {
|
||||
color: $grey;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
strong { color: $grey-lighter; }
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
position: static;
|
||||
max-width: calc(100vw - 2rem);
|
||||
|
||||
.table-of-contents-item {
|
||||
display: flex;
|
||||
flex-direction: row-reverse;
|
||||
justify-content: start;
|
||||
|
||||
strong {
|
||||
display: inline;
|
||||
margin: 0 0 0 0.75rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,9 +7,18 @@ code { color: #{$grey-dark}; }
|
|||
}
|
||||
}
|
||||
|
||||
a[target=_blank]::after {
|
||||
a{
|
||||
&[target=_blank]::after {
|
||||
content: "⇗";
|
||||
margin-left: 0.25em;
|
||||
}
|
||||
& > code {
|
||||
border-bottom: 1px solid $primary;
|
||||
&:hover {
|
||||
background-color: $primary;
|
||||
color: $white;
|
||||
}
|
||||
}
|
||||
}
|
||||
h1 a.anchor,
|
||||
h2 a.anchor,
|
||||
|
@ -49,4 +58,8 @@ p + p { margin-top: 1rem; }
|
|||
h2 { margin-left: 0; }
|
||||
article { margin-left: 0; }
|
||||
}
|
||||
|
||||
@media screen and (min-width: $widescreen) {
|
||||
.section {
|
||||
padding: 3rem 0rem;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
$body-size: 18px;
|
||||
$body-size: 24px;
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -60,7 +60,7 @@ $menu-width: 360px;
|
|||
hr { background-color: var(--menu-divider); }
|
||||
|
||||
.is-anchor {
|
||||
font-size: 0.85em;
|
||||
font-size: 0.75em;
|
||||
& a::before {
|
||||
content: '# ';
|
||||
color: var(--menu-contrast);
|
||||
|
@ -68,6 +68,7 @@ $menu-width: 360px;
|
|||
}
|
||||
.menu-label { margin-bottom: 1rem; }
|
||||
li.is-group > a {
|
||||
font-size: 0.85rem;
|
||||
&::after {
|
||||
content: '';
|
||||
position: relative;
|
||||
|
@ -119,3 +120,14 @@ $menu-width: 360px;
|
|||
}
|
||||
.burger { display: block; }
|
||||
}
|
||||
|
||||
.menu-list li ul {
|
||||
margin: 0;
|
||||
padding-left: 0;
|
||||
}
|
||||
.menu-list ul li:not(.is-anchor) {
|
||||
margin-left: 0.75em;
|
||||
}
|
||||
.menu-list .menu-list li a {
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
|
|
@ -17,6 +17,7 @@ from .plugins.hook import Hook
|
|||
from .plugins.mermaid import Mermaid
|
||||
from .plugins.notification import Notification
|
||||
from .plugins.span import span
|
||||
from .plugins.inline_directive import inline_directive
|
||||
from .plugins.tabs import Tabs
|
||||
from .text import slugify
|
||||
|
||||
|
@ -55,10 +56,12 @@ class DocsRenderer(HTMLRenderer):
|
|||
)
|
||||
|
||||
def link(self, text: str, url: str, title: str | None = None) -> str:
|
||||
url = self.safe_url(url).removesuffix(".md")
|
||||
if not url.endswith("/"):
|
||||
url = self.safe_url(url).replace(".md", ".html")
|
||||
url, anchor = url.split("#", 1) if "#" in url else (url, None)
|
||||
if not url.endswith("/") and not url.endswith(".html"):
|
||||
url += ".html"
|
||||
|
||||
if anchor:
|
||||
url += f"#{anchor}"
|
||||
attributes: dict[str, str] = {"href": url}
|
||||
if title:
|
||||
attributes["title"] = safe_entity(title)
|
||||
|
@ -90,6 +93,22 @@ class DocsRenderer(HTMLRenderer):
|
|||
attrs["class"] = "table is-fullwidth is-bordered"
|
||||
return self._make_tag("table", attrs, text)
|
||||
|
||||
def inline_directive(self, text: str, **attrs) -> str:
|
||||
num_dots = text.count(".")
|
||||
display = self.codespan(text)
|
||||
|
||||
if num_dots <= 1:
|
||||
return display
|
||||
|
||||
module, *_ = text.rsplit(".", num_dots - 1)
|
||||
href = f"/api/{module}.html"
|
||||
return self._make_tag(
|
||||
"a",
|
||||
{"href": href, "class": "inline-directive"},
|
||||
display,
|
||||
)
|
||||
|
||||
|
||||
def _make_tag(
|
||||
self, tag: str, attributes: dict[str, str], text: str | None = None
|
||||
) -> str:
|
||||
|
@ -126,6 +145,7 @@ _render_markdown = create_markdown(
|
|||
"mark",
|
||||
"table",
|
||||
span,
|
||||
inline_directive,
|
||||
],
|
||||
)
|
||||
|
||||
|
|
|
@ -108,13 +108,30 @@ def _get_object_type(obj) -> str:
|
|||
def organize_docobjects(package_name: str) -> dict[str, str]:
|
||||
page_content: defaultdict[str, str] = defaultdict(str)
|
||||
docobjects = _extract_docobjects(package_name)
|
||||
page_registry: defaultdict[str, list[str]] = defaultdict(list)
|
||||
for module, docobject in docobjects.items():
|
||||
builder = Builder(name="Partial")
|
||||
_docobject_to_html(docobject, builder)
|
||||
ref = module.rsplit(".", module.count(".") - 1)[0]
|
||||
page_registry[ref].append(module)
|
||||
page_content[f"/api/{ref}.md"] += str(builder)
|
||||
for ref, objects in page_registry.items():
|
||||
page_content[f"/api/{ref}.md"] = _table_of_contents(objects) + page_content[f"/api/{ref}.md"]
|
||||
return page_content
|
||||
|
||||
def _table_of_contents(objects: list[str]) -> str:
|
||||
builder = Builder(name="Partial")
|
||||
with builder.div(class_="table-of-contents"):
|
||||
builder.h3("Table of Contents", class_="is-size-4")
|
||||
for obj in objects:
|
||||
module, name = obj.rsplit(".", 1)
|
||||
builder.a(
|
||||
E.strong(name), E.small(module),
|
||||
href=f"#{slugify(obj.replace('.', '-'))}",
|
||||
class_="table-of-contents-item",
|
||||
)
|
||||
return str(builder)
|
||||
|
||||
|
||||
def _extract_docobjects(package_name: str) -> dict[str, DocObject]:
|
||||
docstrings = {}
|
||||
|
@ -310,7 +327,10 @@ def _render_params(builder: Builder, params: list[DocstringParam]) -> None:
|
|||
E.br(),
|
||||
E.span(
|
||||
param.type_name,
|
||||
class_="has-text-weight-normal has-text-purple ml-2",
|
||||
class_=(
|
||||
"has-text-weight-normal has-text-purple "
|
||||
"is-size-7 ml-2"
|
||||
),
|
||||
),
|
||||
]
|
||||
dt_args.extend(parts)
|
||||
|
|
18
guide/webapp/display/plugins/inline_directive.py
Normal file
18
guide/webapp/display/plugins/inline_directive.py
Normal file
|
@ -0,0 +1,18 @@
|
|||
import re
|
||||
|
||||
from mistune.markdown import Markdown
|
||||
|
||||
DIRECTIVE_PATTERN = r":(?:class|func|meth|attr|exc|mod|data|const|obj|keyword|option|cmdoption|envvar):`(?P<ref>sanic\.[^`]+)`" # noqa: E501
|
||||
|
||||
def _parse_inline_directive(inline, m: re.Match, state):
|
||||
state.append_token(
|
||||
{
|
||||
"type": "inline_directive",
|
||||
"attrs": {},
|
||||
"raw": m.group("ref"),
|
||||
}
|
||||
)
|
||||
return m.end()
|
||||
|
||||
def inline_directive(md: Markdown):
|
||||
md.inline.register("inline_directive", DIRECTIVE_PATTERN, _parse_inline_directive, before="escape",)
|
|
@ -62,7 +62,10 @@ def create_app(root: Path) -> Sanic:
|
|||
language: str,
|
||||
path: str = "",
|
||||
):
|
||||
return html(page_renderer.render(request, language, path))
|
||||
return html(
|
||||
page_renderer.render(request, language, path),
|
||||
headers={"vary": "hx-request"},
|
||||
)
|
||||
|
||||
@app.on_request
|
||||
async def set_language(request: Request):
|
||||
|
|
55
sanic/app.py
55
sanic/app.py
|
@ -119,8 +119,59 @@ class Sanic(
|
|||
StartupMixin,
|
||||
metaclass=TouchUpMeta,
|
||||
):
|
||||
"""
|
||||
The main application instance
|
||||
"""The main application instance
|
||||
|
||||
You will create an instance of this class and use it to register
|
||||
routes, listeners, middleware, blueprints, error handlers, etc.
|
||||
|
||||
By convention, it is often called `app`. It must be named using
|
||||
the `name` parameter and is roughly constrained to the same
|
||||
restrictions as a Python module name, however, it can contain
|
||||
hyphens (`-`).
|
||||
|
||||
```python
|
||||
# will cause an error because it contains spaces
|
||||
Sanic("This is not legal")
|
||||
```
|
||||
|
||||
```python
|
||||
# this is legal
|
||||
Sanic("Hyphens-are-legal_or_also_underscores")
|
||||
```
|
||||
|
||||
Args:
|
||||
name (str): The name of the application. Must be a valid
|
||||
Python module name (including hyphens).
|
||||
config (Optional[config_type]): The configuration to use for
|
||||
the application. Defaults to `None`.
|
||||
ctx (Optional[ctx_type]): The context to use for the
|
||||
application. Defaults to `None`.
|
||||
router (Optional[Router]): The router to use for the
|
||||
application. Defaults to `None`.
|
||||
signal_router (Optional[SignalRouter]): The signal router to
|
||||
use for the application. Defaults to `None`.
|
||||
error_handler (Optional[ErrorHandler]): The error handler to
|
||||
use for the application. Defaults to `None`.
|
||||
env_prefix (Optional[str]): The prefix to use for environment
|
||||
variables. Defaults to `SANIC_`.
|
||||
request_class (Optional[Type[Request]]): The request class to
|
||||
use for the application. Defaults to `Request`.
|
||||
strict_slashes (bool): Whether to enforce strict slashes.
|
||||
Defaults to `False`.
|
||||
log_config (Optional[Dict[str, Any]]): The logging configuration
|
||||
to use for the application. Defaults to `None`.
|
||||
configure_logging (bool): Whether to configure logging.
|
||||
Defaults to `True`.
|
||||
dumps (Optional[Callable[..., AnyStr]]): The function to use
|
||||
for serializing JSON. Defaults to `None`.
|
||||
loads (Optional[Callable[..., Any]]): The function to use
|
||||
for deserializing JSON. Defaults to `None`.
|
||||
inspector (bool): Whether to enable the inspector. Defaults
|
||||
to `False`.
|
||||
inspector_class (Optional[Type[Inspector]]): The inspector
|
||||
class to use for the application. Defaults to `None`.
|
||||
certloader_class (Optional[Type[CertLoader]]): The certloader
|
||||
class to use for the application. Defaults to `None`.
|
||||
"""
|
||||
|
||||
__touchup__ = (
|
||||
|
|
Loading…
Reference in New Issue
Block a user