Example #1
0
def create_template(templates: Templates, tmpdir_factory,
                    dirname: str) -> TemplateWrapper:
    templates_dir = tmpdir_factory.mktemp(dirname)

    template = templates_dir.join("hello.html")
    template.write("<h1>Hello, {{ name }}!</h1>")

    templates.directory = str(templates_dir)

    return TemplateWrapper(
        name="hello.html",
        context={"name": "Bocadillo"},
        rendered="<h1>Hello, Bocadillo!</h1>",
        root=str(templates_dir),
    )
from bocadillo import App, Templates, static, view
from models import *

# Initialize app
app = App(static_dir=None)
templates = Templates(app, directory='../app/static/dist')
###### Please make sure to use env variables as this information should be private #########
db.bind(provider='postgres',
        user='******',
        password='******',
        host='postgres',
        database='yourdbname')
#^^^^^ Please make sure to use env variables as this information should be private ^^^^^^###
db.generate_mapping(create_tables=True)


# Create index route
@app.route("/")
# Allow post and get methods (only get is allowed by default)
@view(methods=['POST', 'GET'])
async def homepage(req, res):
    # Check if a post request is inbound
    if 'POST' in req.method:
        # Grab the data from the form of the post request
        data = await req.form()
        # Use function defined in models to add obj to database
        add_animal(name=data['name'], age=data['age'])
        print(data)

    with orm.db_session:
        dbquery = orm.select((a.age, a.name) for a in Animal)[:]
Example #3
0
# chat/app.py
from bocadillo import App, provider, Templates

app = App()
templates = Templates()


@provider(scope="app")
async def history() -> list:
    return []


@provider(scope="app")
async def clients() -> set:
    return set()


@app.websocket_route("/chat", value_type="json")
async def chat(ws, history, clients):
    # Register new client
    print("New client:", ws)
    clients.add(ws)

    # Send history of messages.
    for message in history:
        await ws.send(message)

    try:
        # Broadcast incoming messages to all connected clients.
        async for message in ws:
            print("Received:", message)
Example #4
0
def test_use_without_app():
    templates = Templates()
    assert templates.render_string("foo") == "foo"
Example #5
0
def test_render_string(templates: Templates):
    html = templates.render_string("<h1>{{ title }}</h1>", title="Hello")
    assert html == "<h1>Hello</h1>"
Example #6
0
def test_render_sync(template_file: TemplateWrapper, templates: Templates):
    html = templates.render_sync(template_file.name, **template_file.context)
    assert html == template_file.rendered
Example #7
0
def fixture_templates(app: App):
    return Templates(app)
Example #8
0
# app.py
from bocadillo import App, Templates

app = App()
templates = Templates(app)


@app.websocket_route("/chat", value_type="json")
async def chat(ws, history, clients):
    # Register new client
    print("New client:", ws)
    clients.add(ws)

    # Send history of messages.
    for message in history:
        await ws.send(message)

    try:
        # Broadcast incoming messages to all connected clients.
        async for message in ws:
            print("Received:", message)
            history.append(message)
            if message["type"] == "message":
                for client in clients:
                    await client.send(message)
    finally:
        # Make sure we unregister the client in case of unexpected errors.
        # For example, Safari seems to improperly close WebSockets when
        # leaving the page, returning a 1006 close code instead of 1001.
        print("Disconnected unexpectedly:", ws)
        clients.remove(ws)
Example #9
0
import time

from bocadillo import App, Templates

from . import settings

app = App()
templates = Templates(app, directory=settings.TEMPLATES_DIR)


@app.route("/")
async def index(req, res):
    res.html = await templates.render("index.html")


@app.route("/api/message")
async def get_message(req, res):
    now = time.strftime("%I:%M:%S %p")
    message = f"Hello from the Bocadillo server! The time is {now}."
    res.json = {"message": message}
Example #10
0
def test_modify_context():
    templates = Templates(context={"initial": "stuff"})
    templates.context = {"key": "value"}
    templates.context["foo"] = "bar"
    assert (templates.render_string("{{ foo }}, {{ key }} and {{ initial }}")
            == "bar, value and ")
Example #11
0
def fixture_templates():
    return Templates()
Example #12
0
"""Application definition."""
from bocadillo import App, discover_providers, Templates, static

app = App()
discover_providers("chatbot.providerconf")
templates = Templates(app, directory='dist')
app.mount(prefix='js', app=static('dist/js'))
app.mount(prefix='css', app=static('dist/css'))


# Create routes here.
@app.route('/')
async def index(req, res):
    res.html = await templates.render("index.html")


@app.websocket_route("/conversation")
async def converse(ws, diego, save_client):
    async for message in ws:
        response = diego.get_response(message)
        await ws.send(str(response))


@app.route("/client-count")
async def client_count(req, res, clients):
    res.json = {"count": len(clients)}