最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Backend start problems unicodedecodeerror - Stack Overflow

programmeradmin3浏览0评论

I'm currently in the process of programming an app. I have to say that I'm more or less a complete beginner. But I want to do it anyway.

For a week now i've been stuck with the backend (i have the frontend and it seems to be running) the backend just won't start. i've asked the ai, searched for solutions here in the forum... nothing really helped. I did find something, but apparently the solution is not optimal. utf-8 = ISO-8859-1, because the problem is simply ignored, but not solved.

Can anyone help me?

This is shown in the prompt:

C:\Users\train\Desktop\App\backend>python app.pyTraceback (most recent call last):
File "C:\Users\train\Desktop\App\backend\app.py", line 433, in <module>db.create_all()  # Create database tables^^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\flask_sqlalchemy\extension.py", line 900, in create_allself._call_for_binds(bind_key, "create_all")
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\flask_sqlalchemy\extension.py", line 881, in _call_for_bindsgetattr(metadata, op_name)(bind=engine)
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\sql\schema.py", line 5868, in create_allbind._run_ddl_visitor(
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\engine\base.py", line 3252, in _run_ddl_visitorwith self.begin() as conn:^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\contextlib.py", line 137, in enterreturn next(self.gen)^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\engine\base.py", line 3242, in beginwith self.connect() as conn:^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\engine\base.py", line 3278, in connectreturn self._connection_cls(self)^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\engine\base.py", line 146, in initself._dbapi_connection = engine.raw_connection()^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\engine\base.py", line 3302, in raw_connectionreturn self.pool.connect()^^^^^^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\pool\base.py", line 445, in connectreturn _ConnectionFairy._checkout(self)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\pool\base.py", line 1259, in _checkoutfairy = _ConnectionRecord.checkout(pool)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\pool\base.py", line 708, in checkoutrec = pool._do_get()^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\pool\impl.py", line 179, in _do_getwith util.safe_reraise():^^^^^^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\util\langhelpers.py", line 146, in exitraise exc_value.with_traceback(exc_tb)
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\pool\impl.py", line 177, in _do_getreturn self._create_connection()^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\pool\base.py", line 386, in _create_connectionreturn _ConnectionRecord(self)^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\pool\base.py", line 670, in initself.__connect()
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\pool\base.py", line 896, in __connectwith util.safe_reraise():^^^^^^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\util\langhelpers.py", line 146, in exitraise exc_value.with_traceback(exc_tb)
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\pool\base.py", line 892, in __connectself.dbapi_connection = connection = pool.invoke_creator(self)^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\engine\create.py", line 643, in connectreturn dialect.connect(*cargs, **cparams)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\sqlalchemy\engine\default.py", line 621, in connectreturn self.loaded_dbapi.connect(*cargs, **cparams)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\train\AppData\Local\Programs\Python\Python312\Lib\site-packages\psycopg2_init.py", line 122, in connectconn = _connect(dsn, connection_factory=connection_factory, **kwasync)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfc in position 97: invalid start byte

I've asked the AI, searched for solutions here in the forum. utf-8 = ISO-8859-1, update the flask, psycopg2-binary, python, postgresql-17.2-3, changed the uri and coded it.

that the backend is running and I can send jwt token.

Lewis:Please edit your question to include a minimal reproducible example so that readers can run your code to answer your question.

thank you for your reply and your attempt to help me. I will be happy to give you more information. here is a PART of the main file of the backend. app.py
i hope it is correct like this

from datetime import datetime, timedelta
from flask import Flask, request, jsonify
from flask_socketio import SocketIO, emit
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import threading
import time
import jwt
import requests
from functools import wraps
import json

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": ["http://localhost:3000", "http://localhost:3001"]}})

with open('config.json') as config_file:
    config = json.load(config_file)

app.config['SECRET_KEY'] = config['jwt']['secret_key']
app.config['SQLALCHEMY_DATABASE_URI'] = config['database']['uri']
db = SQLAlchemy(app)
socketio = SocketIO(app)


def get_public_key(token):
    jwks_url = config['oauth_provider']['jwks_url']
    jwks = requests.get(jwks_url).json()
    unverified_header = jwt.get_unverified_header(token)
    rsa_key = {}
    for key in jwks['keys']:
        if key['kid'] == unverified_header['kid']:
            rsa_key = {
                'kty': key['kty'],
                'kid': key['kid'],
                'use': key['use'],
                'n': key['n'],
                'e': key['e']
            }
    return rsa_key

def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = request.headers.get('Authorization')
        if not token:
            return jsonify({'message': 'Token is missing!'}), 403

        try:
            rsa_key = get_public_key(token)
            data = jwt.decode(
                token,
                rsa_key,
                algorithms=[config['jwt']['algorithm']],
                audience=config['jwt']['audience'],
                issuer=config['jwt']['issuer']
            )
        except Exception as e:
            return jsonify({'message': 'Token is invalid!'}), 403

        return f(*args, **kwargs)
    
    return decorated

@app.route('/')
def home():
    return "Hallo, Flask!"

this is the config.json file

     {
    "oauth_provider": {
        "client_id": "your-production-client-id",
        "client_secret": "your-production-client-secret",
        "authorize_url": ";,
        "token_url": ";,
        "redirect_uri": ";,
        "scopes": ["openid", "profile", "email"],
        "jwks_url": "/.well-known/jwks.json"
    },
    
    "jwt": {
        "secret_key": "-----BEGIN PRIVATE KEY-----\nMIIEv...\n-----END PRIVATE KEY-----",
        "algorithm": "RS256",
        "audience": "your-production-audience",
        "issuer": "/"
    },
    "database": {
        "uri": "postgresql+psycopg2://user:password@localhost/dbname"
    }
}             

this is from the SQL (psql) shellServer

Server [localhost]: SHOW server_encoding;
Database [postgres]: SHOW server_encoding;
Port [5432]:
发布评论

评论列表(0)

  1. 暂无评论