Reputation: 869
I'm very new to Python. I'm trying to make a simple web server that pulls data from my mongodb
DB.
This is my files architecture:
This is my code:
# Database
CONNECTION_URL = os.environ['mongoConnectionURL']
DATABASE_NAME = os.environ['mongoDatabaseName']
NEWS_COLLECTION = os.environ['mongodbNewsCollection']
app = FastAPI()
# TODO JS has next function i'm currently unaware of
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_headers=["Origin, X-Requested-With, Content-Type, Accept"],
)
@app.get('/')
def index():
return 'See /entries'
@app.get('/entries')
def getEntries():
client = MongoClient(CONNECTION_URL)
databaseMongo = client.get_database(DATABASE_NAME)
collectionMongo = databaseMongo.get_collection(NEWS_COLLECTION)
result = list(collectionMongo.find())
for entry in result:
return {
'data': result
}
if __name__ == "__main__":
uvicorn.run(app, port=os.environ['PORT'])
This is my error:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/logging/__init__.py", line 1083, in emit
msg = self.format(record)
File "/usr/local/lib/python3.9/logging/__init__.py", line 927, in format
return fmt.format(record)
File "/usr/local/lib/python3.9/logging/__init__.py", line 663, in format
record.message = record.getMessage()
File "/usr/local/lib/python3.9/logging/__init__.py", line 367, in getMessage
msg = msg % self.args
TypeError: %d format: a number is required, not str
The longer error log is:
Upvotes: 1
Views: 2223
Reputation: 139
I think that's because port is an str instead of an int - try changing the last line into:
uvicorn.run(app, port=int(os.environ['PORT']))
Upvotes: 1
Reputation: 33298
uvicorn.run(app, port=os.environ['PORT'])
That line is causing the problem. port
needs to be an integer, but you're passing it as a string.
Convert it to an integer by wrapping the value in int()
, like this:
uvicorn.run(app, port=int(os.environ['PORT']))
Upvotes: 3