Ошибка Django API REST с использованием Postman: «подробно»: «Учетные данные для аутентификации не были предоставлены».

#django

#django

Вопрос:

Редактировать

 Operations to perform:
  Apply all migrations: admin, auth, authtoken, contenttypes, sessions
Running migrations:
  Applying authtoken.0001_initial... OK
  Applying authtoken.0002_auto_20160226_1747... OK
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagement__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagement__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagementbase.py", line 336, in run_from_argv       
    connections.close_all()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbutils.py", line 224, in close_all
    connection.close()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3base.py", line 248, in close
    if not self.is_in_memory_db():
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3base.py", line 367, in is_in_memory_db 
    return self.creation.is_in_memory_db(self.settings_dict['NAME'])
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3creation.py", line 12, in is_in_memory_db
    return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'WindowsPath' is not iterable
  

Я узнал о Django API REST и реализовал проект quickstart (https://www.django-rest-framework.org/tutorial/quickstart /).
Локально это работает нормально, но я хотел бы использовать API с Postman, но это не работает

Я получил 401 несанкционированную ошибку, я пытаюсь добавить ключ DEFAULT_AUTHENTICATION_CLASSES в settings.py но доза не работает ни

settings.py

 INSTALLED_APPS = [
    'rest_framework',
    'rest_framework.authtoken',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}
  

более того, у меня огромная обратная трассировка в терминале при сохранении проектов (ниже), даже если py manage.py runserver работает

 Traceback (most recent call last):
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libwsgirefhandlers.py", line 138, in run
    self.finish_response()
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libwsgirefhandlers.py", line 196, in finish_response
    self.close()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoreserversbasehttp.py", line 111, in close
    super().close()
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libwsgirefsimple_server.py", line 38, in close
    SimpleHandler.close(self)
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libwsgirefhandlers.py", line 334, in close
    self.result.close()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangohttpresponse.py", line 252, in close
    signals.request_finished.send(sender=self._handler_class)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodispatchdispatcher.py", line 175, in send
    for receiver in self._live_receivers(sender)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodispatchdispatcher.py", line 175, in <listcomp>
    for receiver in self._live_receivers(sender)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodb__init__.py", line 57, in close_old_connections
    conn.close_if_unusable_or_obsolete()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendsbasebase.py", line 514, in close_if_unusable_or_obsolete
    self.close()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3base.py", line 248, in close
    if not self.is_in_memory_db():
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3base.py", line 367, in is_in_memory_db 
    return self.creation.is_in_memory_db(self.settings_dict['NAME'])
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3creation.py", line 12, in is_in_memory_db
    return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'WindowsPath' is not iterable
[02/Sep/2020 16:34:13] "GET /users/ HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 57191)
Traceback (most recent call last):
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libwsgirefhandlers.py", line 138, in run
    self.finish_response()
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libwsgirefhandlers.py", line 196, in finish_response
    self.close()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoreserversbasehttp.py", line 111, in close
    super().close()
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libwsgirefsimple_server.py", line 38, in close
    SimpleHandler.close(self)
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libwsgirefhandlers.py", line 334, in close
    self.result.close()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangohttpresponse.py", line 252, in close
    signals.request_finished.send(sender=self._handler_class)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodispatchdispatcher.py", line 175, in send
    for receiver in self._live_receivers(sender)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodispatchdispatcher.py", line 175, in <listcomp>
    for receiver in self._live_receivers(sender)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodb__init__.py", line 57, in close_old_connections
    conn.close_if_unusable_or_obsolete()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendsbasebase.py", line 514, in close_if_unusable_or_obsolete
    self.close()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3base.py", line 248, in close
    if not self.is_in_memory_db():
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3base.py", line 367, in is_in_memory_db 
    return self.creation.is_in_memory_db(self.settings_dict['NAME'])
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3creation.py", line 12, in is_in_memory_db
    return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'WindowsPath' is not iterable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libsocketserver.py", line 650, in process_request_thread
    self.finish_request(request, client_address)
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libsocketserver.py", line 360, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libsocketserver.py", line 720, in __init__
    self.handle()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoreserversbasehttp.py", line 171, in handle
    self.handle_one_request()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoreserversbasehttp.py", line 194, in handle_one_request 
    handler.run(self.server.get_app())
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libwsgirefhandlers.py", line 145, in run
    self.handle_error()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoreserversbasehttp.py", line 116, in handle_error       
    super().handle_error()
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libwsgirefhandlers.py", line 381, in handle_error
    self.finish_response()
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libwsgirefhandlers.py", line 184, in finish_response
    self.write(data)
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libwsgirefhandlers.py", line 287, in write
    self.send_headers()
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libwsgirefhandlers.py", line 344, in send_headers
    if not self.origin_server or self.client_is_modern():
  File "C:Usersjl3.PRT-063AppDataLocalProgramsPythonPython37-32libwsgirefhandlers.py", line 357, in client_is_modern
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable
----------------------------------------
D:Usersjl3DevSpaceapi_djangotutorialsettings.py changed, reloading.
Traceback (most recent call last):
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagementbase.py", line 323, in run_from_argv       
    self.execute(*args, **cmd_options)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagementcommandsrunserver.py", line 60, in execute
    super().execute(*args, **options)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagementbase.py", line 364, in execute
    output = self.handle(*args, **options)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagementcommandsrunserver.py", line 95, in handle 
    self.run(**options)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagementcommandsrunserver.py", line 102, in run   
    autoreload.run_with_reloader(self.inner_run, **options)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangoutilsautoreload.py", line 598, in run_with_reloader       
    start_django(reloader, main_func, *args, **kwargs)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangoutilsautoreload.py", line 583, in start_django
    reloader.run(django_main_thread)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangoutilsautoreload.py", line 301, in run
    self.run_loop()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangoutilsautoreload.py", line 307, in run_loop
    next(ticker)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangoutilsautoreload.py", line 355, in tick
    self.notify_file_changed(filepath)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangoutilsautoreload.py", line 330, in notify_file_changed     
    trigger_reload(path)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangoutilsautoreload.py", line 218, in trigger_reload
    sys.exit(3)
SystemExit: 3

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagement__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagement__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagementbase.py", line 336, in run_from_argv       
    connections.close_all()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbutils.py", line 224, in close_all
    connection.close()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3base.py", line 248, in close
    if not self.is_in_memory_db():
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3base.py", line 367, in is_in_memory_db 
    return self.creation.is_in_memory_db(self.settings_dict['NAME'])
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3creation.py", line 12, in is_in_memory_db
    return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'WindowsPath' is not iterable
Traceback (most recent call last):
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagementbase.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagementcommandsrunserver.py", line 60, in execute
    super().execute(*args, **options)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagementbase.py", line 364, in execute
    output = self.handle(*args, **options)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagementcommandsrunserver.py", line 95, in handle 
    self.run(**options)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagementcommandsrunserver.py", line 102, in run   
    autoreload.run_with_reloader(self.inner_run, **options)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangoutilsautoreload.py", line 601, in run_with_reloader       
    sys.exit(exit_code)
SystemExit: 1

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagement__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagement__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangocoremanagementbase.py", line 336, in run_from_argv       
    connections.close_all()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbutils.py", line 224, in close_all
    connection.close()
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3base.py", line 248, in close
    if not self.is_in_memory_db():
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3base.py", line 367, in is_in_memory_db 
    return self.creation.is_in_memory_db(self.settings_dict['NAME'])
  File "C:Usersjl3.PRT-063DesktopPythonDjangoenvlibsite-packagesdjangodbbackendssqlite3creation.py", line 12, in is_in_memory_db
    return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'WindowsPath' is not iterable
  

Ответ №1:

Сначала вам нужно будет создать токен для пользователя, от имени которого вы пытаетесь войти в систему.

 from rest_framework.authtoken.models import Token

token = Token.objects.create(user=...)
print(token.key)
  

Затем вы хотите включить этот токен в заголовок вашего URL

 curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'
  

Вот некоторая документация, просмотренная в разделе TokenAuthentication.
https://www.django-rest-framework.org/api-guide/authentication /

В post man вы можете просто щелкнуть поле заголовка и ввести там свой токен. Это должно аутентифицировать вас, вам просто нужно сначала сгенерировать токен для вашего пользователя.

Вот ссылка на некоторую документацию о том, как работать с распространенными типами аутентификации с postman. https://learning.postman.com/docs/sending-requests/authorization/#basic-auth

Ответ №2:

Попробуйте это.

 python3 manage.py migrate
  

Комментарии:

1. хорошо, это работает. Не знаю, почему это не было точно указано в руководстве…

2. django-rest-framework.org/api-guide/authentication/…

3. надеюсь, это поможет. ps: можете ли вы пометить вопрос как решенный / проголосовать за ответ