使用依赖注入器。以下是您的应用程序的样子。
application.py
清单:
import json
from dependency_injector import containers, providers
from dependency_injector.ext import flask
from flask import Flask
class Response:
def __init__(self, data):
self.data = data
def json(self):
return self.data
class GooglePlacesSearchProvider:
def __init__(self, url, api_key):
...
def get_by_phone_number(self, phone, language):
return Response({'result': 'phone-number-lookup-result'})
def get_by_address(self, phone, language):
return Response({'result': 'address-lookup-result'})
def search_with_phone_number(phone: str, language: str, places_provider: GooglePlacesSearchProvider):
resp = places_provider.get_by_phone_number(phone, language)
return from_response(resp)
def search_with_address(address: str, language: str, places_provider: GooglePlacesSearchProvider):
resp = places_provider.get_by_address(address, language)
return from_response(resp)
def from_response(resp: Response):
return json.dumps(resp.json(), ensure_ascii=False)
class ApplicationContainer(containers.DeclarativeContainer):
"""Application container."""
app = flask.Application(Flask, __name__, instance_relative_config=True)
config = providers.Configuration()
places_provider = providers.Factory(
GooglePlacesSearchProvider,
config.services.places.url,
config.services.places.api_key,
)
search_with_phone_number_view = flask.View(
search_with_phone_number,
places_provider=places_provider,
)
search_with_address_view = flask.View(
search_with_address,
places_provider=places_provider,
)
def create_app():
container = ApplicationContainer()
container.config.from_yaml('config.yml')
container.config.services.places.api_key.from_env('PLACES_API_KEY')
app = container.app()
app.container = container
app.add_url_rule(
'/search/phone/<phone>/<language>',
view_func=container.search_with_phone_number_view.as_view(),
)
app.add_url_rule(
'/search/address/<address>/<language>',
view_func=container.search_with_address_view.as_view(),
)
return app
if __name__ == '__main__':
HOST = 'localhost'
PORT = 5000
app = create_app()
app.run(HOST, PORT)
config.yml
清单:
services:
places:
url: "https://maps.googleapis.com/maps/api/place/findplacefromtext/json"
当您运行应用程序时,需要将API密钥作为环境变量提供:
PLACES_API_KEY=key python -m application
我建议将其拆分为多个文件。请查看依赖注入器Flask教程。