aws / chalice

Python Serverless Microframework for AWS
Apache License 2.0
10.66k stars 1.01k forks source link

Routes in multiple python files #881

Open luisdemarchi opened 6 years ago

luisdemarchi commented 6 years ago

Can I create multiple files with routes? I would like to separate by "modules" and each module be a folder with the routes and all scripts. In the release note of 0.4 it is commented that the "chalicelib" folder has been added but does not speak if I can get the routes from the "app.pyf".

As I understand it, what I can do is create all the routes in the main file and make imports and each auxiliary function. But I do not think it would be a clean project when I hit 40 API calls.

A current test: (importing the scripts only when the correct function is requested)

app.py

app.route('/recordings',
           methods=['POST'])
def create_recording():
    from chalicelib.polly_s3 import synthesize_speech, upload_to_s3, index_in_dynamodb;

    request = app.current_request
    body = request.json_body
    record_id = str(uuid.uuid4())
    text = body.get("text")
    voice = 'Vitoria'

    synthesize_speech(record_id, text, voice)
    url = upload_to_s3(record_id, S3_BUCKET)
    item = index_in_dynamodb(record_id, text, voice, url, DYNAMO_DB_TABLE)
    return [item]

I wonder if this is a viable solution:

app.py: import chalicelib

chalicelib > init.py: from . import users, teams

chalicelib > users > init.py: from . import route

chalicelib > users > route.py:

from app import app
from . import controller

@app.route("/users/test")
def test():
    return controller.test()
stealthycoin commented 6 years ago

This won't work currently because the actual handler function needs to be located in app.py. Its intended to be the one place all your route information is stored in. I'll mark this as a feature request.

luisdemarchi commented 6 years ago

@stealthycoin I'm glad that this could go into a queue for improvements, but you see, the way I did it apparently works: I imported the app object from app.py into the final file, there I did the decorator and it worked.

Now the question is: If my system has 6 "modules", in this logic, will it load my costs with AWS? I ask this, because what I understand is that each call the system will load 100% of my code and will spend more RAM, to perform a simple function lambda. No?