用于数据处理和 Postgres post 的 Heroku API

问题描述 投票:0回答:1

我正在尝试编写我的第一个 API。我(在 GPT 的帮助下)编写了一个简单的请求脚本,并将 Dash-API 脚本上传到 Heroku。我从多个远程位置获取输入,并且希望将远程数据添加到通用 Postgres 数据库中。由于存在各种安全层,我不确定 Heroku dash 式应用程序是否可以用作 API。这可能吗?我知道 Heroku 有一个平台 API,但它的目的是用于其他用途。到目前为止,我的错误代码表明以下内容,所以我不确定我的方法是否错误或我的代码错误。谢谢。:

response content: b'<!doctype html>\n<html lang=en>\n<title>405 Method Not Allowed</title>\n<h1>Method Not Allowed</h1>\n<p>The method is not allowed for the requested URL.</p>\n'

import requests

data = {
    "sensor": "temperature",
    "value": 25.5
}


api_endpoint = 'https://my_app.herokuapp.com/ingest'  
token = 'too_many_secrets'

headers = {'Authorization': f'Bearer {token}'}

response = requests.post(api_endpoint, json=data, headers=headers, verify=True)

if response.status_code == 200:
    print("Data sent successfully")
else:
    print(f"Failed to send data. Status code: {response.status_code}")
    print(f'response content: {response.content}')

我的 Heroku API 应用程序

from flask import Flask, request, jsonify
from flask_cors import CORS
import dash
from dash import dcc, html, Input, Output
import json

app = Flask(__name__)
CORS(app)
dash_app = dash.Dash(__name__,)
server = dash_app.server

valid_tokens = ["too_many_secrets"]

dash_app.layout = html.Div(children=[
    html.H1(children='Simple Dash App'),
    dcc.Link('Ingest Data', href='/ingest'),
    html.Div(id='output-message')
])

# Dash callback for the Dash route
@dash_app.callback(
    Output('output-message', 'children'),
    Input('url', 'pathname')
)
def display_page(pathname):
    if pathname == '/ingest':
        # This part is for Dash and the URL handling you've defined
        return html.Div()

# Flask route for the traditional Flask endpoint
@app.route('/ingest', methods=['OPTIONS', 'POST'])
def handle_ingest():
    if request.method == 'OPTIONS':
        response = make_response()
        response.headers.add('Access-Control-Allow-Origin', '*')  # Adjust this to your needs
        response.headers.add('Access-Control-Allow-Headers', 'Authorization, Content-Type')
        response.headers.add('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        return response

    # Continue with your existing logic for POST requests
    token = request.headers.get('Authorization')
    if token in valid_tokens:
        data = request.json  # Assuming the data is sent as JSON

        # Perform data validation and write to the database here
        # Example: Write data to your Heroku Postgres database

        print("Success: Data ingested successfully")
        return jsonify({"message": "Data ingested successfully"})
    else:
        print("Unauthorized user: Your token was Invalid")
        return jsonify({"message": "Unauthorized"}), 401

if __name__ == '__main__':
    app.run(debug=True)
python plotly-dash heroku-postgres
1个回答
0
投票

好吧,经过一周的摇头之后。我想我明白了。 dash 应用程序需要 Procfile 指向 Gunicorn 服务器的入口。

web: gunicorn your_module_name:server

但是,对于 Flask 应用程序,Procfile 需要:

web: gunicorn your_module_name:app

运行 dash 应用程序似乎会阻止 Flask API 工作。不要同时尝试男孩和女孩。

© www.soinside.com 2019 - 2024. All rights reserved.