Reputation: 3209
I'm getting the error : TypeError: __init__() missing 1 required positional argument
The entire error is:
[2021-09-04 22:00:53,162] ERROR in app: Exception on /entry/title [GET]
Traceback (most recent call last):
File "/Users/shakur/PycharmProjects/flaskProject2/venv/lib/python3.9/site-packages/flask/app.py", line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/shakur/PycharmProjects/flaskProject2/venv/lib/python3.9/site-packages/flask/app.py", line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/Users/shakur/PycharmProjects/flaskProject2/venv/lib/python3.9/site-packages/flask_restful/__init__.py", line 467, in wrapper
resp = resource(*args, **kwargs)
File "/Users/shakur/PycharmProjects/flaskProject2/venv/lib/python3.9/site-packages/flask/views.py", line 82, in view
self = view.view_class(*class_args, **class_kwargs) # type: ignore
TypeError: __init__() missing 1 required positional argument: 'title'
127.0.0.1 - - [04/Sep/2021 22:00:53] "GET /entry/title HTTP/1.1" 500 -
For some reason the get request is throwing an error, I'm at a loss on why... no idea. Any suggestions would be appreciated
from flask import Flask
from flask_restful import Resource, Api
import sqlite3
app = Flask(__name__)
app.secret_key = "xyz"
api = Api(app)
class Entry(Resource):
def __init__(self, title, language="Python", attempts=0,wins=0):
self.title = title
self.language = language
self.attempts = attempts
self.wins = wins
def __repr__(self):
#...
def record_attempts_and_wins(self, a, w=0):
#...
@classmethod
def find_entry_by_title(cls, title):
connection = sqlite3.connect("data.db")
cursor = connection.cursor()
query = "SELECT * FROM entries WHERE title=?"
result = cursor.execute(query, (title,))
column = result.fetchone()
if column:
entry = cls(*column)
else:
entry = None
connection.close()
return entry
def get(self, title):
entry = Entry.find_entry_by_title(self, title)
return entry
api.add_resource(Entry, "/entry/<string:title>")
Upvotes: 0
Views: 571
Reputation: 92440
Flask doesn't know that you have added positional arguments to the Resource
subclass. When you call:
api.add_resource(Entry, "/entry/<string:title>")
it just thinks Entry
will be a Resource
, which doesn't have a title
argument in its constructor. How could it know it needs to pass a title
when it calls the Entry()
constructor?
This is addressed in the docs for passing constructor parameters into resources. You need to tell it what to pass as a title:
api.add_resource(Entry, "/entry/<string:title>", resource_class_kwargs={ 'title': "some title" })
Upvotes: 5