0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

firebase cloudfunctions上のpython関数をローカルでテストする

Last updated at Posted at 2021-03-11

おそらくgcloudのツールとかを使ってローカルに仮想環境作ったりするのが順当な手順なんだと思うが、めんどくさかったのでflaskの test_request_context()を使った。

以下がcloudfunctionsのhello_world関数

def hello_world(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
    """
    request_json = request.get_json()
    if request.args and 'message' in request.args:
        return request.args.get('message')
    elif request_json and 'message' in request_json:
        return request_json['message']
    else:
        return f'Hello World!'

これを動かすにはこのようにすれば良い

import flask

app = flask.Flask(__name__)

@app.route('/test/')
def hello_world(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
    """
    request_json = request.get_json()
    if request.args and 'message' in request.args:
        return request.args.get('message')
    elif request_json and 'message' in request_json:
        return request_json['message']
    else:
        return f'Hello World!'

if __name__ == '__main__':
    with app.test_request_context('/test/'):
        response = hello_world(flask.request)
        print(f'{response}')
    with app.test_request_context('/test?message=hello_hello_how_low?'):
        response = hello_world(flask.request)
        print(f'{response}')
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?