I had a hard time trying to get Python (Flask) to work with NOW. The official document is also hard to see, so I will summarize it again.
If you just run Flask, this works. The important point is the builds of now.json.
index.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "hello"
requirements.txt
flask==1.0.2
now.json
{
"version": 2,
"builds": [{ "src": "index.py", "use": "@now/python" }]
}
Suppose you add a routing to index.py that handles / hello
.
index.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "hello"
@app.route("/hello")
def world():
return "world"
If you deploy in this state and access / hello
, it will be 404.
To handle it properly, edit now.json and add routes. Now any request will be processed by wsgi root.
now.json
{
"version": 2,
"builds": [{ "src": "index.py", "use": "@now/python" }],
"routes": [{ "src": "/.*", "dest": "/" }]
}
Since routes have been added, any request that does not exist will be processed via Flask.
You can customize it by looking at Custom Error Page in Flask Official Documentation
index.py
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")
def index():
return "hello"
@app.route("/hello")
def world():
return "world"
@app.errorhandler(404)
def resource_not_found(e):
return jsonify(error=str(e)), 404
Recommended Posts