Code Monkey home page Code Monkey logo

flask-app-on-azure-functions's Introduction

page_type languages products description title author urlFragment
sample
python
azure
azure-functions
This is a sample Azure Function app created with the Flask framework.
Using Flask Framework with Azure Functions
vrdmr, shreyabatra4
azure-functions-python-create-flask-app

Using Flask Framework with Azure Functions

Azure Functions supports WSGI and ASGI-compatible frameworks with HTTP-triggered Python functions. This can be helpful if you are familiar with a particular framework, or if you have existing code you would like to reuse to create the Function app. The following is an example of creating an Azure Function app using Flask.

Prerequisites

Here are some of the prerequisites to get this sample to work for you.

Install Python

A Python version that is supported by Azure Functions is required. Run python --version (Linux/MacOS) or py --version (Windows) to check your Python version reports to a supported version. For more information on installing Python, see How to install Python.

Install Azure Functions Core Tools

Azure Functions Core Tools provides commands to create functions, connect to Azure, and deploy function projects. For more information, see Install Azure Functions Core Tools.

Create a new Azure Function App in VS Code

To create an Azure Function app in VSCode, please go through the Microsoft Docs tutorial on creating your first Azure Function using Visual Studio Code. In the code snippet along with the sample, we name the two python module 'FlaskApp' and 'HandleApproach' with the HTTP trigger.

Setup

Clone or download this sample repository, and open the sample folder in Visual Studio Code or your IDE of choice.

Flask Framework in an Azure Function App

The file requirements.txt is updated to include the following depdendencies.

azure-functions
Flask

Note that azure-functions-worker should not be included in this file as the Python worker is manager by Azure Functions platform and manually managing it may cause unexpected issues.

The following code shows the use of WsgiMiddleware, which redirects the invocations to Flask handler.

import azure.functions as func
from FlaskApp import app

def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
    """Each request is redirected to the WSGI handler.
    """
    return func.WsgiMiddleware(app.wsgi_app).handle(req, context)

The file function.json is modified to include route in the HTTP trigger.

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ],
      "route": "/{*route}"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ]
}

The file host.json is updated to include the HTTP routePrefix.

{
  "version": "2.0",
  "extensions": {
    "http": {
        "routePrefix": ""
    }
  }
}

Running the sample

Testing locally

To run Function Apps using Core Tools, see Run functions locally with Core Tools.

To test locally, run the below to install Flask.

pip install -r requirements.txt

Then, start debug mode and test the function using the HTTP endpoint exposed after the host and the worker load up the function.

Http Functions:
HandleApproach: [GET,POST] http://localhost:7071/<route>

Testing in Azure

You can publish the function app directly from VSCode using the “Publish to Azure option” in the Azure extension. For more information, please refer the guide to publish the project to Azure using Visual Studio Code.

You can use a tool like Postman to see the API in action locally, and on Azure. Running locally will help you to verify the credentials, configuration and business logic.

Calling the URL with Path Parameters

When running this sample, you can try a different URL route as well as parameterize it. For instance, http://<HOST>:7071/hello/Foo to call the Flask app with path param Foo. Another option is have the route as module to provide import guidance, which can be done through changing the url to http://<HOST>:7071/module.

When done locally, please try the following URL in your browser -

http://localhost:7071/hello/Foo

When done in Azure, please try the following URL in your browser -

http://<FunctionAppName>.azurewebsites.net/hello/Foo

Conclusion and Next Steps

This sample helps you setup an app with the Flask framework and can help you get started using web frameworks in Azure Functions.

To learn more about altering Python functions to leverage WSGI and ASGI-compatible frameworks, see Web frameworks.

flask-app-on-azure-functions's People

Contributors

microsoft-github-operations[bot] avatar microsoftopensource avatar shreyabatra4 avatar vrdmr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask-app-on-azure-functions's Issues

404 http://localhost:7071/

I am following your tutorial the only difference is i got a app.py under root project folder instead of a package
it seems it wont redirect request to my backend app


if __name__ == "__main__":
    # 初始化logs.txt
    date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    with open('logs.txt', 'a') as f:
        f.write("time: " + date + " " + "reload again!" + '\n')

    app.add_url_rule('/', 'webio_view', webio_view(partial(main, lang='')),
                     methods=['GET', 'POST', 'OPTIONS'])
    app.add_url_rule('/en', 'webio_view_en', webio_view(partial(main, lang='en')),
                     methods=['GET', 'POST', 'OPTIONS'])
    app.add_url_rule('/zh', 'webio_view_zh', webio_view(partial(main, lang='zh')),
                     methods=['GET', 'POST', 'OPTIONS'])  
    app.add_url_rule('/es', 'webio_view_es', webio_view(partial(main, lang='es')),
                     methods=['GET', 'POST', 'OPTIONS'])  
#vietnam 
    app.add_url_rule('/vi', 'webio_view_vi', webio_view(partial(main, lang='vi')),
                     methods=['GET', 'POST', 'OPTIONS'])    
#Philippines   
    app.add_url_rule('/fil', 'webio_view_fil', webio_view(partial(main, lang='fil')),
                     methods=['GET', 'POST', 'OPTIONS'])    
    app.add_url_rule('/ru', 'webio_view_ru', webio_view(partial(main, lang='ru')),
                     methods=['GET', 'POST', 'OPTIONS'])    


    if (os.environ.get('PORT')):
        port = int(os.environ.get('PORT'))
    else:
        port = 5000
        
    app.run(host='0.0.0.0', port=port)

import azure.functions as func
from app  import app


def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:

    return func.WsgiMiddleware(app.wsgi_app).handle(req, context)
{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "route": "{*route}",      
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post",
        "options"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ]
}

full log will be

  functions_wsgi: [GET,POST,OPTIONS] http://localhost:7071/{*route}

For detailed output, run func with --verbose flag.
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/2 POST http://127.0.0.1:9314/AzureFunctionsRpcMessages.FunctionRpc/EventStream application/grpc -
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
      Executing endpoint 'gRPC - /AzureFunctionsRpcMessages.FunctionRpc/EventStream'       
[2022-03-13T02:21:36.760Z] Worker process started and initialized.
[2022-03-13T02:21:45.771Z] Executing 'Functions.functions_wsgi' (Reason='This function was programmatically called via the host APIs.', Id=6d1219ae-7e69-4497-9ea8-3fb8e0126caf)      
[2022-03-13T02:21:45.871Z] Executed 'Functions.functions_wsgi' (Succeeded, Id=6d1219ae-7e69-4497-9ea8-3fb8e0126caf, Duration=121ms)
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
      Executed endpoint 'gRPC - /AzureFunctionsRpcMessages.FunctionRpc/EventStream'        
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
      Request finished HTTP/2 POST http://127.0.0.1:9314/AzureFunctionsRpcMessages.FunctionRpc/EventStream application/grpc - - 200 - application/grpc 119441.4867ms
info: Grpc.AspNetCore.Server.ServerCallHandler[14]
      Error reading message.
      System.IO.IOException: The request stream was aborted.
       ---> Microsoft.AspNetCore.Connections.ConnectionAbortedException: The HTTP/2 connection faulted.
       ---> Microsoft.AspNetCore.Connections.ConnectionResetException: 远程主机强迫关闭了一个现有的连接。
       ---> System.Net.Sockets.SocketException (10054): 远程主机强迫关闭了一个现有的连接。 
         at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Internal.SocketAwaitableEventArgs.<GetResult>g__ThrowSocketException|5_0(SocketError e)
         at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Internal.SocketAwaitableEventArgs.GetResult(Int16 token)
         at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Internal.SocketConnection.DoReceive()
         --- End of inner exception stack trace ---
         at System.IO.Pipelines.Pipe.GetReadResult(ReadResult& result)
         at System.IO.Pipelines.Pipe.GetReadAsyncResult()
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2Connection.ReadInputAsync()
         at System.IO.Pipelines.Pipe.GetReadResult(ReadResult& result)
         at System.IO.Pipelines.Pipe.GetReadAsyncResult()
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2Connection.ProcessRequestsAsync[TContext](IHttpApplication`1 application)
         --- End of inner exception stack trace ---
         --- End of inner exception stack trace ---
         at System.IO.Pipelines.Pipe.GetReadResult(ReadResult& result)
         at System.IO.Pipelines.Pipe.GetReadAsyncResult()
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2MessageBody.ReadAsync(CancellationToken cancellationToken)
         at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)    
         at Grpc.AspNetCore.Server.Internal.PipeExtensions.ReadStreamMessageAsync[T](PipeReader input, HttpContextServerCallContext serverCallContext, Func`2 deserializer, CancellationToken cancellationToken)
info: Microsoft.AspNetCore.Server.Kestrel[32]
      Connection id "0HMG4J0PIU3PJ", Request id "0HMG4J0PIU3PJ:00000001": the application completed without reading the entire request body.
[2022-03-13T02:23:37.564Z] File 'C:\Program Files\dotnet\dotnet.exe' is not found, 'dotnet' invocation will rely on the PATH environment variable.
[2022-03-13T02:23:37.663Z] File 'C:\Program Files\dotnet\dotnet.exe' is not found, 'dotnet' invocation will rely on the PATH environment variable.
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/2 POST http://127.0.0.1:9314/AzureFunctionsRpcMessages.FunctionRpc/EventStream application/grpc -
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
      Executing endpoint 'gRPC - /AzureFunctionsRpcMessages.FunctionRpc/EventStream'    

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.