Меню

Psycopg2 errors invalidtextrepresentation ошибка ошибочный литерал массива

Я новичок в python django. И я пытаюсь создать сайт с несколькими вариантами тестирования.
Я вьетнамец, поэтому мои вопросы на вьетнамском языке.

У меня возникла проблема, когда я пытаюсь вставить объект Answers в базу данных.

Моя ошибка:

django.db.utils.DataError: malformed array literal: "{"A": "Cu01a1m", "B": "chu00e1o"}"
LINE 1: ...answer", "level") VALUES ('Hôm nay ăn gì', '', 1, '{"A": "C...
                                                             ^
DETAIL:  Unexpected array element.

Моя POST просьба:

{
    "title": "Hôm năy ăn gì",
    "category": 3,
    "choices": {
        "A": "Cơm",
        "B": "cháo"
    },
    "answer": "A"
}

Вот мой код в models.py:

from django.db import models
from django.contrib.postgres.fields import ArrayField

# Create your models here.

class Category(models.Model):
    title = models.TextField(null=False, blank=False)
    description = models.TextField(null=False, blank=False)
 
class Question(models.Model):
    title = models.TextField(null=False, blank=False)
    description = models.TextField(null=False, blank=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    # choices = ArrayField(ArrayField(models.TextField(blank=True)))
    choices = models.JSONField(null=False, blank=False)
    answer = models.TextField(null=False,blank=False)
    level = models.IntegerField(null=True, blank=True)

В views.py:

from django.db.models import query
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import generics
from rest_framework import viewsets
from app.models import User, Category, Question
from app.serializers import UserSerializer, QuestionSerializer,  CategorySerializer

from django.shortcuts import get_object_or_404

# Create your views here.

class CategoryViewSet(viewsets.ModelViewSet):
    serializer_class = CategorySerializer
    queryset = Category.objects.all()

class QuestionViewSet(viewsets.ModelViewSet):
    serializer_class = QuestionSerializer
    queryset = Question.objects.all()

В serializers.py:

from django.contrib.postgres import fields
from rest_framework import serializers
from app.models import User, Question, Category

class CategorySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Category
        fields = ['id', 'title', 'description']

class QuestionSerializer(serializers.ModelSerializer):
    # category = CategorySerializer(read_only=False)
    class Meta:
        model = Question
        fields = ['id', 'description', 'category', 'choices', 'answer', 'level']

Есть ли решение для меня, чтобы вставить вьетнамский JSON объект в базу данных. Или могу ли я использовать ArrayField вместо JSONField? Если да, то можете ли вы привести мне пример?

Большое спасибо.

Мне кажется, что поле Question модели choices не было изменено с array на json в базе данных. Поэтому то, что вы видите, это:

select '{"A": "Cu01a1m", "B": "chu00e1o"}'::varchar[];
ERROR:  malformed array literal: "{"A": "Cu01a1m", "B": "chu00e1o"}"
LINE 1: select '{"A": "Cu01a1m", "B": "chu00e1o"}'::varchar[];

вместо:

select '{"A": "Cu01a1m", "B": "chu00e1o"}'::jsonb;
           jsonb           
---------------------------
 {"A": "Cơm", "B": "cháo"}

В psql посмотрите на таблицу вопросов и узнайте, что на самом деле представляет собой поле?

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

from django.contrib.postgres.fields import JSONField


class Question(models.Model):
    
    choices = JSONField()

Вернуться на верх

#python #json #django #postgresql #django-rest-framework

Вопрос:

Я новичок в python django. И я пытаюсь создать тестовый сайт с несколькими вариантами ответов. Я вьетнамец, поэтому мои вопросы на вьетнамском языке.

У меня возникли проблемы, когда я пытаюсь вставить ответы на объекты в базу данных.

Моя ошибка:

 django.db.utils.DataError: malformed array literal: "{"A": "Cu01a1m", "B": "chu00e1o"}"
LINE 1: ...answer", "level") VALUES ('Hôm nay ăn gì', '', 1, '{"A": "C...
                                                             ^
DETAIL:  Unexpected array element.
 

Моя POST просьба:

 {
    "title": "Hôm năy ăn gì",
    "category": 3,
    "choices": {
        "A": "Cơm",
        "B": "cháo"
    },
    "answer": "A"
}
 

Вот мой код в models.py :

 from django.db import models
from django.contrib.postgres.fields import ArrayField

# Create your models here.

class Category(models.Model):
    title = models.TextField(null=False, blank=False)
    description = models.TextField(null=False, blank=False)
 
class Question(models.Model):
    title = models.TextField(null=False, blank=False)
    description = models.TextField(null=False, blank=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    # choices = ArrayField(ArrayField(models.TextField(blank=True)))
    choices = models.JSONField(null=False, blank=False)
    answer = models.TextField(null=False,blank=False)
    level = models.IntegerField(null=True, blank=True)
 

В views.py :

 from django.db.models import query
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import generics
from rest_framework import viewsets
from app.models import User, Category, Question
from app.serializers import UserSerializer, QuestionSerializer,  CategorySerializer

from django.shortcuts import get_object_or_404

# Create your views here.

class CategoryViewSet(viewsets.ModelViewSet):
    serializer_class = CategorySerializer
    queryset = Category.objects.all()

class QuestionViewSet(viewsets.ModelViewSet):
    serializer_class = QuestionSerializer
    queryset = Question.objects.all()
 

В serializers.py :

 from django.contrib.postgres import fields
from rest_framework import serializers
from app.models import User, Question, Category

class CategorySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Category
        fields = ['id', 'title', 'description']

class QuestionSerializer(serializers.ModelSerializer):
    # category = CategorySerializer(read_only=False)
    class Meta:
        model = Question
        fields = ['id', 'description', 'category', 'choices', 'answer', 'level']
 

Любое решение для меня, чтобы вставить вьетнамский объект JSON в базу данных. Или я могу использовать arrayField вместо JSONField? Если да, можете ли вы привести мне пример?

Большое спасибо.

Ответ №1:

Мне кажется Question choices , что поле модели не было изменено с array поля на json поле в базе данных. Итак, то, что вы видите, это:

 select '{"A": "Cu01a1m", "B": "chu00e1o"}'::varchar[];
ERROR:  malformed array literal: "{"A": "Cu01a1m", "B": "chu00e1o"}"
LINE 1: select '{"A": "Cu01a1m", "B": "chu00e1o"}'::varchar[];
 

вместо:

 select '{"A": "Cu01a1m", "B": "chu00e1o"}'::jsonb;
           jsonb           
---------------------------
 {"A": "Cơm", "B": "cháo"}
 

В psql посмотрите на таблицу вопросов и посмотрите, что на самом деле представляет собой поле?

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

1. Как я могу это исправить? Можете ли вы дать мне решение?

2. Вы проверили, какой тип столбца находится в базе данных, и если да, то что это такое? Бежать migrate ?. Трудно сказать без дополнительной информации о том, как вы изменили значение с ArrayField на JSONField и есть ли в существующем столбце данные?

3. Я думаю, что мой тип столбца-jsonb. После того, как я побежал migrate , у меня возникла эта проблема django.db.utils.ProgrammingError: cannot cast type text[] to jsonb LINE 1: ...on" ALTER COLUMN "choices" TYPE jsonb USING "choices"::jsonb .

4. Ошибка говорит о том, что текущим типом столбца в базе данных является текстовый массив( text[] ). В модели есть столбец, JSONField который переводится jsonb в базу данных. Очевидно migrate , что он не справится с этим переходом. Я никогда не работал migrate с Django, поэтому я не собираюсь там чем-то помогать. Я бы создал новый вопрос о том, как перенести text[] поле в jsonb одно.

Ответ №2:

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

 from django.contrib.postgres.fields import JSONField


class Question(models.Model):
    
    choices = JSONField()
 

New in version 2.8.

Changed in version 2.8.4: added errors introduced in PostgreSQL 12

Changed in version 2.8.6: added errors introduced in PostgreSQL 13

Changed in version 2.9.2: added errors introduced in PostgreSQL 14

Changed in version 2.9.4: added errors introduced in PostgreSQL 15

This module exposes the classes psycopg raises upon receiving an error from
the database with a SQLSTATE value attached (available in the
pgcode attribute). The content of the module is generated
from the PostgreSQL source code and includes classes for every error defined
by PostgreSQL in versions between 9.1 and 15.

Every class in the module is named after what referred as “condition name” in
the documentation, converted to CamelCase: e.g. the error 22012,
division_by_zero is exposed by this module as the class DivisionByZero.

Every exception class is a subclass of one of the standard DB-API
exception
and expose the Error interface.
Each class’ superclass is what used to be raised by psycopg in versions before
the introduction of this module, so everything should be compatible with
previously written code catching one the DB-API class: if your code used to
catch IntegrityError to detect a duplicate entry, it will keep on working
even if a more specialised subclass such as UniqueViolation is raised.

The new classes allow a more idiomatic way to check and process a specific
error among the many the database may return. For instance, in order to check
that a table is locked, the following code could have been used previously:

try:
    cur.execute("LOCK TABLE mytable IN ACCESS EXCLUSIVE MODE NOWAIT")
except psycopg2.OperationalError as e:
    if e.pgcode == psycopg2.errorcodes.LOCK_NOT_AVAILABLE:
        locked = True
    else:
        raise

While this method is still available, the specialised class allows for a more
idiomatic error handler:

try:
    cur.execute("LOCK TABLE mytable IN ACCESS EXCLUSIVE MODE NOWAIT")
except psycopg2.errors.LockNotAvailable:
    locked = True
psycopg2.errors.lookup(code)

Lookup an error code and return its exception class.

Raise KeyError if the code is not found.

try:
    cur.execute("LOCK TABLE mytable IN ACCESS EXCLUSIVE MODE NOWAIT")
except psycopg2.errors.lookup("55P03"):
    locked = True

SQLSTATE exception classes¶

The following table contains the list of all the SQLSTATE classes exposed by
the module.

Note that, for completeness, the module also exposes all the
DB-API-defined exceptions and a few
psycopg-specific ones
exposed by the extensions
module, which are not listed here.

SQLSTATE

Exception

Base exception

Class 02: No Data (this is also a warning class per the SQL standard)

02000

NoData

DatabaseError

02001

NoAdditionalDynamicResultSetsReturned

DatabaseError

Class 03: SQL Statement Not Yet Complete

03000

SqlStatementNotYetComplete

DatabaseError

Class 08: Connection Exception

08000

ConnectionException

OperationalError

08001

SqlclientUnableToEstablishSqlconnection

OperationalError

08003

ConnectionDoesNotExist

OperationalError

08004

SqlserverRejectedEstablishmentOfSqlconnection

OperationalError

08006

ConnectionFailure

OperationalError

08007

TransactionResolutionUnknown

OperationalError

08P01

ProtocolViolation

OperationalError

Class 09: Triggered Action Exception

09000

TriggeredActionException

DatabaseError

Class 0A: Feature Not Supported

0A000

FeatureNotSupported

NotSupportedError

Class 0B: Invalid Transaction Initiation

0B000

InvalidTransactionInitiation

DatabaseError

Class 0F: Locator Exception

0F000

LocatorException

DatabaseError

0F001

InvalidLocatorSpecification

DatabaseError

Class 0L: Invalid Grantor

0L000

InvalidGrantor

DatabaseError

0LP01

InvalidGrantOperation

DatabaseError

Class 0P: Invalid Role Specification

0P000

InvalidRoleSpecification

DatabaseError

Class 0Z: Diagnostics Exception

0Z000

DiagnosticsException

DatabaseError

0Z002

StackedDiagnosticsAccessedWithoutActiveHandler

DatabaseError

Class 20: Case Not Found

20000

CaseNotFound

ProgrammingError

Class 21: Cardinality Violation

21000

CardinalityViolation

ProgrammingError

Class 22: Data Exception

22000

DataException

DataError

22001

StringDataRightTruncation

DataError

22002

NullValueNoIndicatorParameter

DataError

22003

NumericValueOutOfRange

DataError

22004

NullValueNotAllowed

DataError

22005

ErrorInAssignment

DataError

22007

InvalidDatetimeFormat

DataError

22008

DatetimeFieldOverflow

DataError

22009

InvalidTimeZoneDisplacementValue

DataError

2200B

EscapeCharacterConflict

DataError

2200C

InvalidUseOfEscapeCharacter

DataError

2200D

InvalidEscapeOctet

DataError

2200F

ZeroLengthCharacterString

DataError

2200G

MostSpecificTypeMismatch

DataError

2200H

SequenceGeneratorLimitExceeded

DataError

2200L

NotAnXmlDocument

DataError

2200M

InvalidXmlDocument

DataError

2200N

InvalidXmlContent

DataError

2200S

InvalidXmlComment

DataError

2200T

InvalidXmlProcessingInstruction

DataError

22010

InvalidIndicatorParameterValue

DataError

22011

SubstringError

DataError

22012

DivisionByZero

DataError

22013

InvalidPrecedingOrFollowingSize

DataError

22014

InvalidArgumentForNtileFunction

DataError

22015

IntervalFieldOverflow

DataError

22016

InvalidArgumentForNthValueFunction

DataError

22018

InvalidCharacterValueForCast

DataError

22019

InvalidEscapeCharacter

DataError

2201B

InvalidRegularExpression

DataError

2201E

InvalidArgumentForLogarithm

DataError

2201F

InvalidArgumentForPowerFunction

DataError

2201G

InvalidArgumentForWidthBucketFunction

DataError

2201W

InvalidRowCountInLimitClause

DataError

2201X

InvalidRowCountInResultOffsetClause

DataError

22021

CharacterNotInRepertoire

DataError

22022

IndicatorOverflow

DataError

22023

InvalidParameterValue

DataError

22024

UnterminatedCString

DataError

22025

InvalidEscapeSequence

DataError

22026

StringDataLengthMismatch

DataError

22027

TrimError

DataError

2202E

ArraySubscriptError

DataError

2202G

InvalidTablesampleRepeat

DataError

2202H

InvalidTablesampleArgument

DataError

22030

DuplicateJsonObjectKeyValue

DataError

22031

InvalidArgumentForSqlJsonDatetimeFunction

DataError

22032

InvalidJsonText

DataError

22033

InvalidSqlJsonSubscript

DataError

22034

MoreThanOneSqlJsonItem

DataError

22035

NoSqlJsonItem

DataError

22036

NonNumericSqlJsonItem

DataError

22037

NonUniqueKeysInAJsonObject

DataError

22038

SingletonSqlJsonItemRequired

DataError

22039

SqlJsonArrayNotFound

DataError

2203A

SqlJsonMemberNotFound

DataError

2203B

SqlJsonNumberNotFound

DataError

2203C

SqlJsonObjectNotFound

DataError

2203D

TooManyJsonArrayElements

DataError

2203E

TooManyJsonObjectMembers

DataError

2203F

SqlJsonScalarRequired

DataError

2203G

SqlJsonItemCannotBeCastToTargetType

DataError

22P01

FloatingPointException

DataError

22P02

InvalidTextRepresentation

DataError

22P03

InvalidBinaryRepresentation

DataError

22P04

BadCopyFileFormat

DataError

22P05

UntranslatableCharacter

DataError

22P06

NonstandardUseOfEscapeCharacter

DataError

Class 23: Integrity Constraint Violation

23000

IntegrityConstraintViolation

IntegrityError

23001

RestrictViolation

IntegrityError

23502

NotNullViolation

IntegrityError

23503

ForeignKeyViolation

IntegrityError

23505

UniqueViolation

IntegrityError

23514

CheckViolation

IntegrityError

23P01

ExclusionViolation

IntegrityError

Class 24: Invalid Cursor State

24000

InvalidCursorState

InternalError

Class 25: Invalid Transaction State

25000

InvalidTransactionState

InternalError

25001

ActiveSqlTransaction

InternalError

25002

BranchTransactionAlreadyActive

InternalError

25003

InappropriateAccessModeForBranchTransaction

InternalError

25004

InappropriateIsolationLevelForBranchTransaction

InternalError

25005

NoActiveSqlTransactionForBranchTransaction

InternalError

25006

ReadOnlySqlTransaction

InternalError

25007

SchemaAndDataStatementMixingNotSupported

InternalError

25008

HeldCursorRequiresSameIsolationLevel

InternalError

25P01

NoActiveSqlTransaction

InternalError

25P02

InFailedSqlTransaction

InternalError

25P03

IdleInTransactionSessionTimeout

InternalError

Class 26: Invalid SQL Statement Name

26000

InvalidSqlStatementName

OperationalError

Class 27: Triggered Data Change Violation

27000

TriggeredDataChangeViolation

OperationalError

Class 28: Invalid Authorization Specification

28000

InvalidAuthorizationSpecification

OperationalError

28P01

InvalidPassword

OperationalError

Class 2B: Dependent Privilege Descriptors Still Exist

2B000

DependentPrivilegeDescriptorsStillExist

InternalError

2BP01

DependentObjectsStillExist

InternalError

Class 2D: Invalid Transaction Termination

2D000

InvalidTransactionTermination

InternalError

Class 2F: SQL Routine Exception

2F000

SqlRoutineException

InternalError

2F002

ModifyingSqlDataNotPermitted

InternalError

2F003

ProhibitedSqlStatementAttempted

InternalError

2F004

ReadingSqlDataNotPermitted

InternalError

2F005

FunctionExecutedNoReturnStatement

InternalError

Class 34: Invalid Cursor Name

34000

InvalidCursorName

OperationalError

Class 38: External Routine Exception

38000

ExternalRoutineException

InternalError

38001

ContainingSqlNotPermitted

InternalError

38002

ModifyingSqlDataNotPermittedExt

InternalError

38003

ProhibitedSqlStatementAttemptedExt

InternalError

38004

ReadingSqlDataNotPermittedExt

InternalError

Class 39: External Routine Invocation Exception

39000

ExternalRoutineInvocationException

InternalError

39001

InvalidSqlstateReturned

InternalError

39004

NullValueNotAllowedExt

InternalError

39P01

TriggerProtocolViolated

InternalError

39P02

SrfProtocolViolated

InternalError

39P03

EventTriggerProtocolViolated

InternalError

Class 3B: Savepoint Exception

3B000

SavepointException

InternalError

3B001

InvalidSavepointSpecification

InternalError

Class 3D: Invalid Catalog Name

3D000

InvalidCatalogName

ProgrammingError

Class 3F: Invalid Schema Name

3F000

InvalidSchemaName

ProgrammingError

Class 40: Transaction Rollback

40000

TransactionRollback

OperationalError

40001

SerializationFailure

OperationalError

40002

TransactionIntegrityConstraintViolation

OperationalError

40003

StatementCompletionUnknown

OperationalError

40P01

DeadlockDetected

OperationalError

Class 42: Syntax Error or Access Rule Violation

42000

SyntaxErrorOrAccessRuleViolation

ProgrammingError

42501

InsufficientPrivilege

ProgrammingError

42601

SyntaxError

ProgrammingError

42602

InvalidName

ProgrammingError

42611

InvalidColumnDefinition

ProgrammingError

42622

NameTooLong

ProgrammingError

42701

DuplicateColumn

ProgrammingError

42702

AmbiguousColumn

ProgrammingError

42703

UndefinedColumn

ProgrammingError

42704

UndefinedObject

ProgrammingError

42710

DuplicateObject

ProgrammingError

42712

DuplicateAlias

ProgrammingError

42723

DuplicateFunction

ProgrammingError

42725

AmbiguousFunction

ProgrammingError

42803

GroupingError

ProgrammingError

42804

DatatypeMismatch

ProgrammingError

42809

WrongObjectType

ProgrammingError

42830

InvalidForeignKey

ProgrammingError

42846

CannotCoerce

ProgrammingError

42883

UndefinedFunction

ProgrammingError

428C9

GeneratedAlways

ProgrammingError

42939

ReservedName

ProgrammingError

42P01

UndefinedTable

ProgrammingError

42P02

UndefinedParameter

ProgrammingError

42P03

DuplicateCursor

ProgrammingError

42P04

DuplicateDatabase

ProgrammingError

42P05

DuplicatePreparedStatement

ProgrammingError

42P06

DuplicateSchema

ProgrammingError

42P07

DuplicateTable

ProgrammingError

42P08

AmbiguousParameter

ProgrammingError

42P09

AmbiguousAlias

ProgrammingError

42P10

InvalidColumnReference

ProgrammingError

42P11

InvalidCursorDefinition

ProgrammingError

42P12

InvalidDatabaseDefinition

ProgrammingError

42P13

InvalidFunctionDefinition

ProgrammingError

42P14

InvalidPreparedStatementDefinition

ProgrammingError

42P15

InvalidSchemaDefinition

ProgrammingError

42P16

InvalidTableDefinition

ProgrammingError

42P17

InvalidObjectDefinition

ProgrammingError

42P18

IndeterminateDatatype

ProgrammingError

42P19

InvalidRecursion

ProgrammingError

42P20

WindowingError

ProgrammingError

42P21

CollationMismatch

ProgrammingError

42P22

IndeterminateCollation

ProgrammingError

Class 44: WITH CHECK OPTION Violation

44000

WithCheckOptionViolation

ProgrammingError

Class 53: Insufficient Resources

53000

InsufficientResources

OperationalError

53100

DiskFull

OperationalError

53200

OutOfMemory

OperationalError

53300

TooManyConnections

OperationalError

53400

ConfigurationLimitExceeded

OperationalError

Class 54: Program Limit Exceeded

54000

ProgramLimitExceeded

OperationalError

54001

StatementTooComplex

OperationalError

54011

TooManyColumns

OperationalError

54023

TooManyArguments

OperationalError

Class 55: Object Not In Prerequisite State

55000

ObjectNotInPrerequisiteState

OperationalError

55006

ObjectInUse

OperationalError

55P02

CantChangeRuntimeParam

OperationalError

55P03

LockNotAvailable

OperationalError

55P04

UnsafeNewEnumValueUsage

OperationalError

Class 57: Operator Intervention

57000

OperatorIntervention

OperationalError

57014

QueryCanceled

OperationalError

57P01

AdminShutdown

OperationalError

57P02

CrashShutdown

OperationalError

57P03

CannotConnectNow

OperationalError

57P04

DatabaseDropped

OperationalError

57P05

IdleSessionTimeout

OperationalError

Class 58: System Error (errors external to PostgreSQL itself)

58000

SystemError

OperationalError

58030

IoError

OperationalError

58P01

UndefinedFile

OperationalError

58P02

DuplicateFile

OperationalError

Class 72: Snapshot Failure

72000

SnapshotTooOld

DatabaseError

Class F0: Configuration File Error

F0000

ConfigFileError

InternalError

F0001

LockFileExists

InternalError

Class HV: Foreign Data Wrapper Error (SQL/MED)

HV000

FdwError

OperationalError

HV001

FdwOutOfMemory

OperationalError

HV002

FdwDynamicParameterValueNeeded

OperationalError

HV004

FdwInvalidDataType

OperationalError

HV005

FdwColumnNameNotFound

OperationalError

HV006

FdwInvalidDataTypeDescriptors

OperationalError

HV007

FdwInvalidColumnName

OperationalError

HV008

FdwInvalidColumnNumber

OperationalError

HV009

FdwInvalidUseOfNullPointer

OperationalError

HV00A

FdwInvalidStringFormat

OperationalError

HV00B

FdwInvalidHandle

OperationalError

HV00C

FdwInvalidOptionIndex

OperationalError

HV00D

FdwInvalidOptionName

OperationalError

HV00J

FdwOptionNameNotFound

OperationalError

HV00K

FdwReplyHandle

OperationalError

HV00L

FdwUnableToCreateExecution

OperationalError

HV00M

FdwUnableToCreateReply

OperationalError

HV00N

FdwUnableToEstablishConnection

OperationalError

HV00P

FdwNoSchemas

OperationalError

HV00Q

FdwSchemaNotFound

OperationalError

HV00R

FdwTableNotFound

OperationalError

HV010

FdwFunctionSequenceError

OperationalError

HV014

FdwTooManyHandles

OperationalError

HV021

FdwInconsistentDescriptorInformation

OperationalError

HV024

FdwInvalidAttributeValue

OperationalError

HV090

FdwInvalidStringLengthOrBufferLength

OperationalError

HV091

FdwInvalidDescriptorFieldIdentifier

OperationalError

Class P0: PL/pgSQL Error

P0000

PlpgsqlError

InternalError

P0001

RaiseException

InternalError

P0002

NoDataFound

InternalError

P0003

TooManyRows

InternalError

P0004

AssertFailure

InternalError

Class XX: Internal Error

XX000

InternalError_

InternalError

XX001

DataCorrupted

InternalError

XX002

IndexCorrupted

InternalError

Issue

I am tryng to login the admin on my flask app using ID, when i signup it is taking inputs perfectly, but while getting values from database(postgresql) it showing «DataError» I have taken input as alphanumeric in HTML form

here are my code:

in model.py i have written code for databese to make columns

model.py

class Admin(UserMixin, db.Model):
    id = db.Column(db.String(1000), primary_key=True )
    name = db.Column(db.String(1000))
    email = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(100))
    timestamp = db.Column(db.DateTime)

in this auth.py I writen code for POST methods for signup and login

auth.py

@auth.route('/admin')
def admin():
    return render_template('admin.html')


@auth.route('/admin', methods=['POST'])
def admin_post():
    id = request.form.get('id')
    password = request.form.get('password')
    remember = True if request.form.get('remember') else False

admins = Admin.query.filter_by(id=id).first()

# check if the user actually exists
# take the user-supplied password, hash it, and compare it to the hashed password in the database
if not admins or not check_password_hash(admins.password, password):
    flash('Please check your login details and try again.')
    # if the user doesn't exist or password is wrong, reload the page
    return redirect(url_for('auth.admin'))

# if the above check passes, then we know the user has the right credentials
login_user(admins, remember=remember)
return redirect(url_for('main.adminOP'))


 @auth.route('/admin-signup')
 def adminsignup():
     return render_template('admin-signup.html')


 @auth.route('/admin-signup', methods=['POST'])
 def adminsignup_post():
     id = request.form.get('id')
     email = request.form.get('email')
     name = request.form.get('name')
     password = request.form.get('password')
     timestamp = datetime.now()

# if this returns a admin, then the email already exists in database
admins = Admin.query.filter_by(email=email).first()

if admins:  # if a user is found, we want to redirect back to signup page so user can try again
    flash('Email address already exists')
    return redirect(url_for('auth.adminsignup'))

# create a new user with the form data. Hash the password so the plaintext version isn't saved.
new_admin = Admin(id=id, email=email, name=name,
                  password=generate_password_hash(password, method='sha256'), timestamp=timestamp)

# add the new user to the database
db.session.add(new_admin)
db.session.commit()

return redirect(url_for('auth.admin'))

The error caught in trace back is:

sqlalchemy.exc.DataError: (psycopg2.errors.InvalidTextRepresentation) invalid input syntax for type 
integer: "B1"
LINE 3: WHERE person.id = 'B1'
                          ^

[SQL: SELECT person.id AS person_id, person.email AS person_email, person.password AS person_password, 
person.name AS person_name, person.timestamp AS person_timestamp
FROM person
WHERE person.id = %(pk_1)s]
[parameters: {'pk_1': 'B1'}]
(Background on this error at: http://sqlalche.me/e/14/9h9h)

Here B1 is id

admin-signup.html

As I said earlier I have used alhapanumeric in input field

{% extends "base.html" %}

{% block content %}
<div class="column is-4 is-offset-4">
    <h3 class="title has-text-info">Sign Up</h3>
    <div class="box">
        {% with messages = get_flashed_messages() %}
        {% if messages %}
        <div class="notification is-danger">
            {{ messages[0] }}. Go to <a href="{{ url_for('auth.admin') }}">login page</a>.
        </div>
        {% endif %}
        {% endwith %}
        <form method="POST" action="/admin-signup">
            <div class="field">
                <div class="control has-icons-left has-icons-right">
                    <input class="input is-large" type="text" name="id" placeholder="Your ID" autofocus="" pattern="[a-zA-Z0-9]+"><span
                        class="icon is-small is-left">
                        🆔
                    </span>
                    <small> Remember: ID is you employee number </small>
                </div>
            </div>
            <div class="field">
                <div class="control has-icons-left has-icons-right">
                    <input class="input is-large" type="email" aria-required="true" name="email" placeholder="Email"
                        autofocus=""><span class="icon is-small is-left">
                        📧
                    </span>
                </div>
            </div>

            <div class="field">
                <div class="control has-icons-left has-icons-right">
                    <input class="input is-large" type="text" aria-required="true" name="name" placeholder="Name"
                        autofocus=""><span class="icon is-small is-left">
                        👱
                    </span>
                </div>
            </div>

            <div class="field">
                <div class="control has-icons-left has-icons-right">
                    <input class="input is-large" type="password" aria-required="true" name="password"
                        placeholder="Password"><span class="icon is-small is-left">
                        🔑
                    </span>
                </div>
            </div>

            <button class="button is-block is-info is-large is-fullwidth">Sign Up</button>
        </form>
    </div>
</div>
{% endblock %}

admin.html

{% extends "base.html" %}

{% block content %}
<div class="column is-4 is-offset-4">
    <h3 class="title has-text-info">Admin Login</h3>
    <div class="box">
        {% with messages = get_flashed_messages() %}
        {% if messages %}
        <div class="notification is-danger">
            {{ messages[0] }}
        </div>
        {% endif %}
        {% endwith %}
        <form method="POST" action="/admin">
            <div class="field">
                <div class="control has-icons-left has-icons-right">
                    <input class="input is-large" type="text" name="id" placeholder="Your ID" autofocus="" required pattern="[a-zA-Z0-9]+"><span
                        class="icon is-small is-left">
                        🆔
                    </span>
                    <small> HINT: ID is you employee number </small>
                </div>
            </div>

            <div class="field">
                <div class="control has-icons-left has-icons-right">
                    <input class="input is-large" type="password" name="password" placeholder="Your Password"><span
                        class="icon is-small is-left">
                        🔑
                    </span>
                </div>
            </div>
            <div class="field">
                <label class="checkbox">
                    <input type="checkbox">
                    Remember me
                </label>
            </div>
            <button class="button is-block is-info is-large is-fullwidth">Login</button>
        </form>
    </div>
</div>
{% endblock %}

After editing code i got this same error caught in debugging
enter image description here

this is person model

class person(UserMixin, db.Model):
    # primary keys are required by SQLAlchemy
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(100))
    name = db.Column(db.String(1000))
    timestamp = db.Column(db.DateTime)

Solution

The issue is that the column id from your person model is an Integer, not a string. Your load_user function queries the person model providing a key B1, which can not be converted to Integer.

If you intend to query your Admin model and also query your person model depending on who is logged, you should add an identifier in your user session during login and retrieve it in the load_user function. Check out this question for more details.

But if you need to treat your users differently (User#1 is an admin but User#2 is not), you should really consider using a boolean flag in your model, something like this:

class User(UserMixin, db.Model):
    id = db.Column(db.String(1000), primary_key=True )
    name = db.Column(db.String(1000))
    # ...
    is_admin = db.Column(db.Boolean)

You should really avoid having two user’s models with different types of keys, it can get really messy over time.

If your Flask app tend to grow and have multiple kind of users, you should consider adopt the concept of ‘user roles’. Check out Flask-Principal for this.

Old Answer

The issue is probably because your model and your database aren’t synchronized. In some point the development processes you probably had id = db.Column(db.Integer, primary_key=True) then you ran db.create_all() and then altered the id to id = db.Column(db.String(1000), primary_key=True).

In simple words, Flask believes that id is a string, but PostgreSQL is sure that it is an int. Just to be sure, you could check the DDL of the table person with:

pg_dump -U your_user your_database -t person --schema-only

Note that flask/flask-sqlalchemy does not do automatic migrations, after changing your model you should recreate the database or apply the changes manually (the choice is up to you).

Answered By – Magnun Leno

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Pss10r chm ошибка установки
  • Pss update contacts exception победа ошибка