提问人:qleqs 提问时间:11/2/2023 最后编辑:qleqs 更新时间:11/2/2023 访问量:22
获取未正确检索数据的函数
Get functions not retrieving data appropriately
问:
我的 GET 函数:
def get_order_status(timestamp):
session = DB_SESSION()
timestamp_datetime = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%f%z")
readings = session.query(Order_status).filter(Order_status.date_created <=
timestamp_datetime)
results_list = []
for reading in readings:
result = reading.to_dict()
results_list.append(result)
logger.debug("Retrieved: %s" % result)
logger.info(f"Query for orders after {timestamp} returns {len(results_list)} results")
return results_list, 200
和
def get_order_ETA(timestamp):
session = DB_SESSION()
timestamp_datetime = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%f%z")
readings = session.query(OrderETA).filter(OrderETA.date_created <=
timestamp_datetime)
results_list = []
for reading in readings:
result = reading.to_dict()
results_list.append(result)
logger.debug("Retrieved: %s" % result)
session.close()
logger.info(f"Query for ETAs after {timestamp} returns {len(results_list)} results")
return results_list, 200
当前根据数据库条目的数量返回值为 null 的列表(例如,当数据库有 3 个条目时,值为 null 的 3 个列表的列表) 当我尝试从我的数据库中获取事件时,它应该返回超过时间戳的所有事件的字典
openapi.yaml:
openapi: 3.0.0
info:
description: This API receives real-time event data from a food delivery service
version: "1.0.0"
title: Food delivery
contact:
email: [email protected]
tags:
- name: Customer_Order
description: Any operation that involves or can affect the status or availability of an order
- name: Proximity
description: Any operation that deals with the location status of your order
paths:
/order/status:
post:
tags:
- Customer_Order
summary: Reports a customer's order
operationId: app.report_order_status
description: Adds customer's order
responses:
'201':
description: 'Order received!'
'400':
description: 'Invalid input'
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/OrderStatus'
get:
tags:
- Customer_Order
summary: Retrieves a customer's order based on timestamp
operationId: app.get_order_status
parameters:
- name: timestamp
in: query
description: Retrieve orders added after this timestamp
schema:
type: string
format: date-time
example: 2016-08-29T09:12:33.001Z
responses:
'200':
description: Successfully returned a list of orders
content:
application/json:
schema:
$ref: '#/components/schemas/OrderStatus'
'400':
description: Invalid input
/order/ETA:
post:
tags:
- Proximity
summary: Reports the expected time of arrival
operationId: app.reportETA
description: Calculates the ETA for customer order
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/OrderETA'
responses:
'201':
description: ETA calculated successfully
'400':
description: Invalid input
get:
tags:
- Proximity
summary: Retrieves the ETA details based on timestamp
operationId: app.get_order_ETA
parameters:
- name: timestamp
in: query
description: Retrieve locations added after this timestamp
required: false
schema:
type: string
format: date-time
example: 2016-08-29T09:12:33.001Z
responses:
'200':
description: Successfully returned a list of ETAs
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/OrderETA'
'400':
description: Invalid input
components:
schemas:
OrderStatus:
required:
- OrderID
- CustomerAdress
- timestamp
- OrderType
- RestaurantID
- Tip
- Customer_PhoneNumber
properties:
OrderID:
type: string
format: uuid
example: '7834fhasd7fadsbi'
CustomerAdress:
type: string
example: '123 elm st'
timestamp:
type: string
format: date-time
example: 2016-08-29T09:12:33.001Z
OrderType:
type: string
example: 'Delivery'
RestaurantID:
type: string
example: 'cvasd8-d8caj-d87r'
Tip:
type: integer
example: 5
Customer_PhoneNumber:
type: integer
example: 7784235023
OrderETA:
required:
- OrderID
- CustomerLatitude
- CustomerLongitude
- RestaurantLatitude
- RestaurantLongitude
- DriverLatitude
- DriverLongitude
- OrderType
- Distance
- timestamp
properties:
OrderID:
type: number
example: '732949'
CustomerLatitude:
type: number
example: 48.12345
CustomerLongitude:
type: number
example: -123.67890
RestaurantLatitude:
type: number
example: 49.54321
RestaurantLongitude:
type: number
example: -122.98765
DriverLatitude:
type: number
example: 34.56789
DriverLongitude:
type: number
example: -109.12345
OrderType:
type: string
example: 'Delivery'
Distance:
type: number
example: 5.7
timestamp:
type: string
format: date-time
example: 2016-08-29T09:12:33.001Z
type: object
order_status.py
from sqlalchemy import Column, Integer, String, DateTime
from base import Base
import datetime
class Order_status(Base):
__tablename__ = "Order_status"
OrderID = Column(String(50), primary_key=True)
CustomerAdress = Column(String(100), nullable=False)
timestamp = Column(DateTime, nullable=False)
OrderType = Column(String(50), nullable=False)
RestaurantID = Column(String(50), nullable=False)
Tip = Column(Integer, nullable=True)
date_created = Column(DateTime, nullable=False)
Customer_PhoneNumber = Column(Integer, nullable=False)
def __init__(self, OrderID,CustomerAdress,timestamp,OrderType,RestaurantID,Customer_PhoneNumber,Tip):
self.OrderID = OrderID
self.CustomerAdress = CustomerAdress
self.timestamp = timestamp
self.date_created = datetime.datetime.now()
self.RestaurantID = RestaurantID
self.OrderType = OrderType
self.Customer_PhoneNumber = Customer_PhoneNumber
self.Tip = Tip
def to_dict(self):
dict = {}
dict['OrderID'] = self.OrderID
dict['CustomerAdress'] = self.CustomerAdress
dict['timestamp'] = self.timestamp
dict['RestaurantID'] = self.RestaurantID
dict['OrderType'] = self.OrderType
dict['Tip'] = self.Tip
dict['date_created'] = self.date_created
orderETA.py:
from sqlalchemy import Column, Integer, String, DateTime
from base import Base
import datetime
class OrderETA(Base):
__tablename__ = "OrderETA"
OrderID = Column(Integer, primary_key=True)
CustomerLatitude = Column(Integer, nullable=False)
CustomerLongitude = Column(Integer, nullable=False)
RestaurantLatitude = Column(Integer, nullable=False)
RestaurantLongitude = Column(Integer, nullable=False)
DriverLatitude = Column(Integer, nullable=False)
OrderType = Column(String(50), nullable=False)
DriverLongitude = Column(Integer, nullable=False)
Distance = Column(Integer, nullable=False)
timestamp = Column(String(100), nullable=False)
date_created = Column(DateTime, nullable=False)
def __init__(self, OrderID,CustomerLatitude,CustomerLongitude,RestaurantLatitude,RestaurantLongitude,DriverLatitude,DriverLongitude,OrderType,Distance,timestamp):
self.OrderID = OrderID
self.CustomerLatitude = CustomerLatitude
self.CustomerLongitude = CustomerLongitude
self.DriverLatitude = DriverLatitude
self.DriverLongitude = DriverLongitude
self.Distance = Distance
self.OrderType = OrderType
self.RestaurantLatitude = RestaurantLatitude
self.RestaurantLongitude = RestaurantLongitude
self.timestamp = timestamp
self.date_created = datetime.datetime.now()
def to_dict(self):
dict = {}
dict['OrderID'] = self.OrderID
dict['CustomerLatitude'] = self.CustomerLatitude
dict['CustomerLongitude'] = self.CustomerLongitude
dict['DriverLatitude'] = self.DriverLatitude
dict['DriverLongitude'] = self.DriverLongitude
dict['RestaurantLatitude'] = self.RestaurantLatitude
dict['RestaurantLongitude'] = self.RestaurantLongitude
dict['Distance'] = self.Distance
dict['OrderType'] = self.OrderType
dict['timestamp'] = self.timestamp
dict['date_created'] = self.date_created
app.py
import connexion
from flask import jsonify,request
from connexion import NoContent
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from base import Base
from OrderETA import OrderETA
from Order_status import Order_status
import datetime
import requests
import logging
import logging.config
import uuid
import yaml
import datetime
import json
import requests
# Load configuration from app_conf.yml
with open('storage/app_conf.yml', 'r') as f:
app_config = yaml.safe_load(f)
# Load logging configuration from log_conf.yml
with open('storage/log_conf.yml', 'r') as f:
log_config = yaml.safe_load(f.read())
logging.config.dictConfig(log_config)
# Create a logger
logger = logging.getLogger('basicLogger')
DB_ENGINE = create_engine(
f"mysql+pymysql://{app_config['datastore']['user']}:{app_config['datastore']['password']}@{app_config['datastore']['hostname']}:{app_config['datastore']['port']}/{app_config['datastore']['db']}"
)
Base.metadata.bind = DB_ENGINE
DB_SESSION = sessionmaker(bind=DB_ENGINE)
def report_order_status(body):
trace_id = uuid.uuid4()
session = DB_SESSION()
orders = Order_status(
OrderID=body['OrderID'],
CustomerAdress=body['CustomerAdress'],
timestamp=body['timestamp'],
RestaurantID=body['RestaurantID'],
OrderType=body['OrderType'],
Customer_PhoneNumber=body['Customer_PhoneNumber'],
Tip=body['Tip'],
)
session.add(orders)
session.commit()
session.close()
logger.debug(f"Received event report_order_status request with a trace id of {trace_id}")
return NoContent, 201
def reportETA(body):
trace_id = uuid.uuid4()
session = DB_SESSION()
ETA = OrderETA(
OrderID=body['OrderID'],
CustomerLatitude=body['CustomerLatitude'],
CustomerLongitude=body['CustomerLongitude'],
DriverLatitude=body['DriverLatitude'],
DriverLongitude=body['DriverLongitude'],
RestaurantLatitude=body['RestaurantLatitude'],
RestaurantLongitude=body['RestaurantLongitude'],
Distance=body['Distance'],
OrderType=body['OrderType'],
timestamp=body['timestamp']
)
session.add(ETA)
session.commit()
session.close()
logger.debug(f"Received event report_order_status request with a trace id of {trace_id}")
return NoContent, 201
def get_order_status(timestamp):
session = DB_SESSION()
timestamp_datetime = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%f%z")
readings = session.query(Order_status).filter(Order_status.date_created <=
timestamp_datetime)
results_list = []
for reading in readings:
result = reading.to_dict()
results_list.append(result)
logger.debug("Retrieved: %s" % result)
logger.info(f"Query for orders after {timestamp} returns {len(results_list)} results")
return results_list, 200
def get_order_ETA(timestamp):
session = DB_SESSION()
timestamp_datetime = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%f%z")
readings = session.query(OrderETA).filter(OrderETA.date_created <=
timestamp_datetime)
results_list = []
for reading in readings:
result = reading.to_dict()
results_list.append(result)
logger.debug("Retrieved: %s" % result)
session.close()
logger.info(f"Query for ETAs after {timestamp} returns {len(results_list)} results")
return results_list, 200
app = connexion.FlaskApp(__name__, specification_dir='')
app.add_api("openapi.yml", strict_validation=True, validate_responses=True)
if __name__ == "__main__":
app.run(port=8090)
ive been stuck on this for a while now, cant seem to figure out whats wrong
答: 暂无答案
评论
to_dict