1

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:

enter image description here

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:

enter image description here

2
  • 1
    you don't show the code for getMessage, but briefly, use %s for a string formatting or prefer f-strings or .format() anyways Commented Jun 16, 2022 at 18:01
  • oh, perhaps your port is a string and that message really is from logging (yuck)? try port=int(os.environ['PORT']) Commented Jun 16, 2022 at 18:03

2 Answers 2

3
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'])) 
Sign up to request clarification or add additional context in comments.

Comments

1

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'])) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.