django.db.utils.OperationalError: no such table: django_session
django.db.utils.OperationalError: no such table: django_session
前提:我是初学者[请保持友善和耐心]
当我尝试在终端中使用 运行 命令时,例如:
python manage.py makemigrations audioma_manager
或
python manage.py runserver
或
python manage.py migrate
或
python manage.py --run-syncdb
哪里
audioma_manager是我的项目名称
我也尝试使用我的应用程序的名称
我得到了这个异常代码,我在网上搜索了很多,但任何一种解决方案都适用于我的问题:
Traceback (most recent call last):
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: django_session
The above exception was the direct cause of the following exception:
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:\Users371\AudioManVenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle
self.check(databases=[database])
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 423, in check
databases=databases,
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 412, in check
for pattern in self.url_patterns:
File "C:\Users371\AudioManVenv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users371\AudioManVenv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users371\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users371\audioma_manager\audioma_manager\urls.py", line 20, in <module>
path('transcription_form/', include('transcription_form.urls')),
File "C:\Users371\AudioManVenv\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users371\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users371\audioma_manager\transcription_form\urls.py", line 2, in <module>
from .views import upload
File "C:\Users371\audioma_manager\transcription_form\views.py", line 4, in <module>
from .forms import UploadForm
File "C:\Users371\audioma_manager\transcription_form\forms.py", line 5, in <module>
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
File "C:\Users371\audioma_manager\transcription_form\client_transcpition_api.py", line 48, in call_api
session_stored = s.load()
File "C:\Users371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 43, in load
s = self._get_session_from_db()
File "C:\Users371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 34, in _get_session_from_db
expire_date__gt=timezone.now()
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 431, in get
num = len(clone)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 262, in __len__
self._fetch_all()
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 51, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_session
这是我的设置文件(我使用 django-environ 来保密一些变量):
import environ
import os
from pathlib import Path
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
DJANGO_SETTINGS_MODULE="audioma_manager.settings"
# Set the project base directory
BASE_DIR = Path(__file__).resolve().parent.parent
# Take environment variables from .env file
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))
# False if not in os.environ because of casting above
DEBUG = env('DEBUG')
# Raises Django's ImproperlyConfigured
# exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')
# Parse database connection url strings
# like psql://user:pass@127.0.0.1:8458/db
#For production
#DATABASES = {
# read os.environ['DATABASE_URL'] and raises
# ImproperlyConfigured exception if not found
#
# The db() method is an alias for db_url().
'default': env.db(),
# read os.environ['SQLITE_URL']
#'extra': env.db_url(
#'SQLITE_URL',
#default='sqlite:///tmp/my-tmp-sqlite.db'
# )
#}
CACHES = {
# Read os.environ['CACHE_URL'] and raises
# ImproperlyConfigured exception if not found.
#
# The cache() method is an alias for cache_url().
'default': env.cache(),
#instance of sensibile data from .env file
}
API_URL= {
env('API_URL')
}
API_VERSION={
env('API_VERSION')
}
API_USERNAME={
env('API_USERNAME')
}
API_PASSWORD={
env('API_PASSWORD')
}
API_ENDPOINT_SOURCES={
env('API_ENDPOINT_SOURCES')
}
DEFAULT_DIR_PATH={
env('DEFAULT_DIR_PATH')
}
DEFAULT_NAME_FILE_PATTERN={
env('DEFAULT_NAME_FILE_PATTERN')
}
API_ENDPOINT_LOGIN={
env('API_ENDPOINT_LOGIN')
}
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'transcription_form',
'corsheaders',
'rest_framework'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware'
]
ROOT_URLCONF = 'audioma_manager.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'audioma_manager.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
#Local db for tests
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
'USER': 'USER',
'PASSWORD': 'PASS',
'HOST': '127.0.0.1',
'PORT': 3306
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'INFO',
'class': 'logging.FileHandler',
'filename': '\Users\39371\audioma_manager\audioma_manager\logs\debug.log',
},
},
'loggers': {
'transcription_form.client_transcription_api': {
'handlers': ['file'],
'level': 'INFO'
},
},
}
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'http://localhost:8080',
)
我的客户:
from audioma_manager.settings import API_ENDPOINT_LOGIN, API_PASSWORD, API_URL, API_USERNAME, API_VERSION
from django.contrib.sessions.backends.db import SessionStore
import requests
from requests.structures import CaseInsensitiveDict
#class API management
class GetAPISources:
#authentication to aziendal api
def auth_api(self):
url = API_URL + API_VERSION + API_ENDPOINT_LOGIN
auth_email = API_USERNAME
auth_password = API_PASSWORD
list_of_auth = [auth_email,auth_password]
response= requests.post(url,list_of_auth)
if response.status_code==400:
#manage exception code; return null
return False
token=response['token']
#instance of SessionStore
s=SessionStore()
s['auth_token']=token
# saves the current token
s.save()
#implement a method who calls API endpoint from InfojuiceAPi with representation=1
def call_api(self,endpoint):
api_repr='&representation=1'
s=SessionStore()
session_stored = s.load()
auth_token=session_stored['auth_token']
#used endpoint so i can customize the type of endpoint everytime i call the function
#example--> endpoint='/sources' ; endpoint='/customers'
url = API_URL + API_VERSION + endpoint + api_repr
headers = CaseInsensitiveDict()
headers["Accept"]="application/json"
headers["Authorization"]="token " + auth_token
response= requests.get(url,headers=headers)
if response.status_code==401:
self.auth_api()
self.call_api(endpoint)
return response
我的模特:
from django.db import models
# Create your models here.
class Transcription(models.Model):
id = models.BigAutoField
file_name = models.CharField(max_length=10000)
created_at = models.DateTimeField(auto_now_add=True, name='created_at')
updated_at = models.DateTimeField(auto_now=True, name='updated_at')
def __str__(self):
return self.file_name
我的表格:
from django import forms
from .client_transcpition_api import GetAPISources
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
class UploadForm(forms.Form):
lang = forms.CharField(label='Lingua', max_length=100, help_text = "Inserisci la lingua del contenuto")
source = forms.CharField(label='Fonte', help_text = "Seleziona la fonte del contenuto" , widget=forms.Select(choices=source_choice))
data = forms.DateField(label='data', help_text = "Seleziona la data del contenuto ", max_length=100)
time = forms.TimeField(label='ora', help_text = "Seleziona l' orario del contenuto", max_length=100)
extension = forms.CharField(label='estensione', help_text = "Seleziona l'estensione del contenuto", max_length=100)
file = forms.FileField(label='file da caricare', help_text = "Seleziona il file da mandare in trascrizione")
我的观点:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadForm
def upload(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = UploadForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# redirect to a new URL:
#this url is only temp, evaluate better how to do
return HttpResponseRedirect('/thanks/')
else:
form = upload()
return render(request, 'upload.html', {'form': form})
我的模板:
<!DOCTYPE html>
{% Block Content %}
<h2>Upload</h2>
<form enctype="multipart/form-data" method="post" action="/foo/">
<!-- we need to use this token bc Django makes security controls and requires this token
to be recognize as trust source of code -->
{% csrf_token %}
{{form}}
<input type="file" name="recupero">
<button type="submit">Invio</button>
</form>
在我的项目中我想:
1)创建存储库、新的 Django 项目并首次提交。
2)安装Django Environ,通过.env文件上传配置。
配置必须允许您配置:
Aziendal API 的身份验证(URL,版本,用户名,密码)
path 保存待转录的新文件的目录
文件名模式(带有用于替换各种组件的占位符,例如日期、源名称、标题、语言、时间)
3) 创建转录模型以保存有关转录中发送的内容的信息。
方案:
ID
file_name 方法(字符串)
created_at(日期时间)
updated_at(日期时间)
4)
为 Aziendal API 实现一个迷你客户端,用于 GET 检索按名称过滤的源,并使用查询参数进行呈现检索。
使用配置文件中配置的身份验证。
5)
实现一个带有表单的页面,以加载包含以下字段的新成绩单:
日期(日期)
来源(select 来源取自 API)
语言(select 取自配置)
标题
可能的配置文件(可选)
请帮助一个年轻的初学者。
如果您需要我的项目的一些源代码,请询问:)
感谢帮助
xoxo
这里最紧迫的问题是您在导入时尝试通过
加载会话来进行数据库调用
File "C:\Users371\audioma_manager\transcription_form\forms.py", line 5, in <module>
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
File "C:\Users371\audioma_manager\transcription_form\client_transcpition_api.py", line 48, in call_api
session_stored = s.load()
File "C:\Users371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 43, in load
s = self._get_session_from_db()
这是 Django 中的一个大禁忌,会导致先有鸡还是先有蛋的问题:
- 您需要进行迁移和 运行 迁移以创建数据库 tables
- Django 需要能够导入您的应用程序才能这样做
- 您的应用程序尝试从目前尚不存在的 table(因为它尚未迁移)进行数据库查询。
您需要 source_choice
在例如__init__
表单时间,而不是导入时间。
目前,您可以将 source_choice=...
行替换为 source_choice=[]
– 您将没有任何来源可供选择,但您可以进行迁移 运行宁.
除此之外,与会话相关的代码看起来很奇怪,尤其是,因为您正试图在请求上下文之外这样做。在这种情况下将不会加载有效会话,因为也没有请求。我认为您可能会将 Django 会话与您正在使用的 API 所要求的任何内容混淆。
前提:我是初学者[请保持友善和耐心] 当我尝试在终端中使用 运行 命令时,例如:
python manage.py makemigrations audioma_manager
或
python manage.py runserver
或
python manage.py migrate
或
python manage.py --run-syncdb
哪里 audioma_manager是我的项目名称
我也尝试使用我的应用程序的名称
我得到了这个异常代码,我在网上搜索了很多,但任何一种解决方案都适用于我的问题:
Traceback (most recent call last):
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: django_session
The above exception was the direct cause of the following exception:
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:\Users371\AudioManVenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle
self.check(databases=[database])
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 423, in check
databases=databases,
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users371\AudioManVenv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 412, in check
for pattern in self.url_patterns:
File "C:\Users371\AudioManVenv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users371\AudioManVenv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users371\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users371\audioma_manager\audioma_manager\urls.py", line 20, in <module>
path('transcription_form/', include('transcription_form.urls')),
File "C:\Users371\AudioManVenv\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users371\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users371\audioma_manager\transcription_form\urls.py", line 2, in <module>
from .views import upload
File "C:\Users371\audioma_manager\transcription_form\views.py", line 4, in <module>
from .forms import UploadForm
File "C:\Users371\audioma_manager\transcription_form\forms.py", line 5, in <module>
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
File "C:\Users371\audioma_manager\transcription_form\client_transcpition_api.py", line 48, in call_api
session_stored = s.load()
File "C:\Users371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 43, in load
s = self._get_session_from_db()
File "C:\Users371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 34, in _get_session_from_db
expire_date__gt=timezone.now()
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 431, in get
num = len(clone)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 262, in __len__
self._fetch_all()
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 51, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users371\AudioManVenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_session
这是我的设置文件(我使用 django-environ 来保密一些变量):
import environ
import os
from pathlib import Path
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
DJANGO_SETTINGS_MODULE="audioma_manager.settings"
# Set the project base directory
BASE_DIR = Path(__file__).resolve().parent.parent
# Take environment variables from .env file
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))
# False if not in os.environ because of casting above
DEBUG = env('DEBUG')
# Raises Django's ImproperlyConfigured
# exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')
# Parse database connection url strings
# like psql://user:pass@127.0.0.1:8458/db
#For production
#DATABASES = {
# read os.environ['DATABASE_URL'] and raises
# ImproperlyConfigured exception if not found
#
# The db() method is an alias for db_url().
'default': env.db(),
# read os.environ['SQLITE_URL']
#'extra': env.db_url(
#'SQLITE_URL',
#default='sqlite:///tmp/my-tmp-sqlite.db'
# )
#}
CACHES = {
# Read os.environ['CACHE_URL'] and raises
# ImproperlyConfigured exception if not found.
#
# The cache() method is an alias for cache_url().
'default': env.cache(),
#instance of sensibile data from .env file
}
API_URL= {
env('API_URL')
}
API_VERSION={
env('API_VERSION')
}
API_USERNAME={
env('API_USERNAME')
}
API_PASSWORD={
env('API_PASSWORD')
}
API_ENDPOINT_SOURCES={
env('API_ENDPOINT_SOURCES')
}
DEFAULT_DIR_PATH={
env('DEFAULT_DIR_PATH')
}
DEFAULT_NAME_FILE_PATTERN={
env('DEFAULT_NAME_FILE_PATTERN')
}
API_ENDPOINT_LOGIN={
env('API_ENDPOINT_LOGIN')
}
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'transcription_form',
'corsheaders',
'rest_framework'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware'
]
ROOT_URLCONF = 'audioma_manager.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'audioma_manager.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
#Local db for tests
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
'USER': 'USER',
'PASSWORD': 'PASS',
'HOST': '127.0.0.1',
'PORT': 3306
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'INFO',
'class': 'logging.FileHandler',
'filename': '\Users\39371\audioma_manager\audioma_manager\logs\debug.log',
},
},
'loggers': {
'transcription_form.client_transcription_api': {
'handlers': ['file'],
'level': 'INFO'
},
},
}
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'http://localhost:8080',
)
我的客户:
from audioma_manager.settings import API_ENDPOINT_LOGIN, API_PASSWORD, API_URL, API_USERNAME, API_VERSION
from django.contrib.sessions.backends.db import SessionStore
import requests
from requests.structures import CaseInsensitiveDict
#class API management
class GetAPISources:
#authentication to aziendal api
def auth_api(self):
url = API_URL + API_VERSION + API_ENDPOINT_LOGIN
auth_email = API_USERNAME
auth_password = API_PASSWORD
list_of_auth = [auth_email,auth_password]
response= requests.post(url,list_of_auth)
if response.status_code==400:
#manage exception code; return null
return False
token=response['token']
#instance of SessionStore
s=SessionStore()
s['auth_token']=token
# saves the current token
s.save()
#implement a method who calls API endpoint from InfojuiceAPi with representation=1
def call_api(self,endpoint):
api_repr='&representation=1'
s=SessionStore()
session_stored = s.load()
auth_token=session_stored['auth_token']
#used endpoint so i can customize the type of endpoint everytime i call the function
#example--> endpoint='/sources' ; endpoint='/customers'
url = API_URL + API_VERSION + endpoint + api_repr
headers = CaseInsensitiveDict()
headers["Accept"]="application/json"
headers["Authorization"]="token " + auth_token
response= requests.get(url,headers=headers)
if response.status_code==401:
self.auth_api()
self.call_api(endpoint)
return response
我的模特:
from django.db import models
# Create your models here.
class Transcription(models.Model):
id = models.BigAutoField
file_name = models.CharField(max_length=10000)
created_at = models.DateTimeField(auto_now_add=True, name='created_at')
updated_at = models.DateTimeField(auto_now=True, name='updated_at')
def __str__(self):
return self.file_name
我的表格:
from django import forms
from .client_transcpition_api import GetAPISources
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
class UploadForm(forms.Form):
lang = forms.CharField(label='Lingua', max_length=100, help_text = "Inserisci la lingua del contenuto")
source = forms.CharField(label='Fonte', help_text = "Seleziona la fonte del contenuto" , widget=forms.Select(choices=source_choice))
data = forms.DateField(label='data', help_text = "Seleziona la data del contenuto ", max_length=100)
time = forms.TimeField(label='ora', help_text = "Seleziona l' orario del contenuto", max_length=100)
extension = forms.CharField(label='estensione', help_text = "Seleziona l'estensione del contenuto", max_length=100)
file = forms.FileField(label='file da caricare', help_text = "Seleziona il file da mandare in trascrizione")
我的观点:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadForm
def upload(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = UploadForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# redirect to a new URL:
#this url is only temp, evaluate better how to do
return HttpResponseRedirect('/thanks/')
else:
form = upload()
return render(request, 'upload.html', {'form': form})
我的模板:
<!DOCTYPE html>
{% Block Content %}
<h2>Upload</h2>
<form enctype="multipart/form-data" method="post" action="/foo/">
<!-- we need to use this token bc Django makes security controls and requires this token
to be recognize as trust source of code -->
{% csrf_token %}
{{form}}
<input type="file" name="recupero">
<button type="submit">Invio</button>
</form>
在我的项目中我想:
1)创建存储库、新的 Django 项目并首次提交。
2)安装Django Environ,通过.env文件上传配置。 配置必须允许您配置: Aziendal API 的身份验证(URL,版本,用户名,密码) path 保存待转录的新文件的目录 文件名模式(带有用于替换各种组件的占位符,例如日期、源名称、标题、语言、时间)
3) 创建转录模型以保存有关转录中发送的内容的信息。 方案: ID file_name 方法(字符串) created_at(日期时间) updated_at(日期时间)
4) 为 Aziendal API 实现一个迷你客户端,用于 GET 检索按名称过滤的源,并使用查询参数进行呈现检索。 使用配置文件中配置的身份验证。
5) 实现一个带有表单的页面,以加载包含以下字段的新成绩单: 日期(日期) 来源(select 来源取自 API) 语言(select 取自配置) 标题 可能的配置文件(可选)
请帮助一个年轻的初学者。 如果您需要我的项目的一些源代码,请询问:) 感谢帮助 xoxo
这里最紧迫的问题是您在导入时尝试通过
加载会话来进行数据库调用 File "C:\Users371\audioma_manager\transcription_form\forms.py", line 5, in <module>
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
File "C:\Users371\audioma_manager\transcription_form\client_transcpition_api.py", line 48, in call_api
session_stored = s.load()
File "C:\Users371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 43, in load
s = self._get_session_from_db()
这是 Django 中的一个大禁忌,会导致先有鸡还是先有蛋的问题:
- 您需要进行迁移和 运行 迁移以创建数据库 tables
- Django 需要能够导入您的应用程序才能这样做
- 您的应用程序尝试从目前尚不存在的 table(因为它尚未迁移)进行数据库查询。
您需要 source_choice
在例如__init__
表单时间,而不是导入时间。
目前,您可以将 source_choice=...
行替换为 source_choice=[]
– 您将没有任何来源可供选择,但您可以进行迁移 运行宁.
除此之外,与会话相关的代码看起来很奇怪,尤其是,因为您正试图在请求上下文之外这样做。在这种情况下将不会加载有效会话,因为也没有请求。我认为您可能会将 Django 会话与您正在使用的 API 所要求的任何内容混淆。