Skip to main content

valar for morghulis

Matching engine 的运行、下单/撤单协议和 WebSocket 事件见 MATCHING_ENGINE.md。

1. installation

  • you need to install valar in a django project
pip install 'valar[daphne]'

Channels 4 使用 Daphne 提供支持 WebSocket 的 manage.py runserver,需将 daphne 放在 INSTALLED_APPS 首位。本仓库开发环境安装依赖使用:

python -m pip install -r requirements.txt

使用 Uvicorn 等其他 ASGI 服务器的宿主项目可以安装基础包 valar,并从 INSTALLED_APPS 中移除 daphne。仅安装基础依赖后运行 Django 自带的 HTTP runserver 不会提供 WebSocket。

2. root app

  • you only need 3 files in your root app
    • settings.py
    • asgi.py
    • urls.py
    • __init__.py

settings.py

from pathlib import Path

""" Compulsory settings """
DEBUG = True
BASE_DIR = Path(__file__).resolve().parent.parent
BASE_APP = str(BASE_DIR.name)
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
SECRET_KEY = 'django-insecure-of@tfouoq^_f$l!yki#m=6j7)@&kjri$1_$!mca-=%7=+@f@5^'

""" Minimized compulsory settings """

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

INSTALLED_APPS = [
    'daphne',
    'django.contrib.sessions',
    "corsheaders",
    'channels',
    'valar.apps.ValarConfig',
]

MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'valar.system.middleware.ValarMiddleware'
]

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels.layers.InMemoryChannelLayer"
    }
}

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
ROOT_URLCONF = "%s.urls" % BASE_APP
ASGI_APPLICATION = "%s.asgi.application" % BASE_APP

""" Optional settings """

ALLOWED_HOSTS = ['*']
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = False
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_AGE = 60 * 60
FILE_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024 * 100
DATA_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024 * 100

""" Valar Options """

VALAR_HANDLER_MAPPING = "%s.urls.channel_mapping" % BASE_APP
VALAR_MINIO_URL = "s3://admin:__password__@___host__:___port___"

""" Email Options """

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.____.com'
EMAIL_PORT = 25
EMAIL_HOST_USER = "______@____.com"
EMAIL_HOST_PASSWORD = '______'

init.py (when using MySQL)

import pymysql

pymysql.install_as_MySQLdb()

asgi.py

import os
from pathlib import Path
from typing import cast, Callable, Any

from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from django.urls import re_path

from valar.system.socket.consumer import ValarConsumer

asgi_router_list = [
    re_path(
        r'(?P<client>\w+)/$',
        cast(Callable[..., Any], ValarConsumer.as_asgi())
    ),
]

os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%s.settings' % Path(__file__).resolve().parent.parent.name)
application = ProtocolTypeRouter({
    'http': get_asgi_application(),
    'websocket': URLRouter(cast(Any, asgi_router_list))
})

urls.py

urlpatterns = [
]

channel_mapping = {
}
  • go to section 4 to see how to register channel handlers (a Vue - Django async communication tool) in urls.

3. migrate

Run the initialization command before starting the server, and again after changing Valar models or metadata definitions:

python manage.py initialize_valar
python manage.py runserver

The command generates and applies Valar migrations and rebuilds Valar metadata. It replaces the previous automatic database setup in AppConfig.ready(), so application initialization and autoreloads no longer query or rewrite the database.

4. how to register a channel handler for Morghulis async methods

4.1 create a handler


4.2 create a dict (e.g. using the name 'channel_mapping') to save your handler

  • I'd like to put it in the root urls.py, you can put it anywhere

4.3 register the channel_mapping in the settings.py


4.4 you can copy the following codes to your urls.py


5. create an orm model extends the AbstractUser class, enable the authentication of Valar

class User(AbstractUser):
    """
        any fields you want
    """
    description = models.TextField(null=True, verbose_name='备注')

    class Meta:
        verbose_name = 'User'

Metadata

Release files for valar 2.0.8

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for valar 2.0.8
File Size Uploaded Provenance Actions
valar-2.0.8.tar.gz 45.4 kB Without provenance Details for valar-2.0.8.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for valar 2.0.8
File Interpreter ABI Platform Actions
valar-2.0.8-py3-none-any.whl Python 3 none any Details for valar-2.0.8-py3-none-any.whl

Total release size: 89.6 kB

Release files / valar-2.0.8.tar.gz

Download URL valar-2.0.8.tar.gz
Size 45.4 kB
Tags Source
SHA-256 checksum
How to use checksums
f05773b363c9d9bd5aab709eb3de9bce05a5db28d450844af995cde644d1c9ba
BLAKE2b-256 checksum
How to use checksums
8657c6c27a3c5fe8807ca9d492faf305d3d17c075b4afe21e6a490f526a9f470
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.14

Release files / valar-2.0.8-py3-none-any.whl

Download URL valar-2.0.8-py3-none-any.whl
Size 44.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
dbac3c7f5c08bd1c44b5df9da76b542bc99230b8e7e23043ae1030a5266079ec
BLAKE2b-256 checksum
How to use checksums
96be1bbea434444a244df3bfe691318f852b85dbfa85e0e53e8212bd74be2caf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.14

Security for valar 2.0.8

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.0.8 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page