Summary of Flask development problems

After graduation, I developed a Web website with the Flask framework. I encountered many problems during the development process. Today, I will make a summary to avoid encountering the same problems in the future.

Question 1

# Problem code 
Error: While importing 'xxx' , an ImportError was raised.

The import statement is wrong. Check the import statement in all py files. One of the possible errors is that the package name is wrong, and the other is that the full path “project name. folder name. The form of file name. function name”
Note that the error when running the project directly with the flask run command is very vague, you can directly run the app.py file on the compiler, so that you can get a clearer error message

Question 2

After running the project with the flask run command on the cloud server, the local input of the cloud server ip cannot be accessed

Add the host address after the run command to listen for all external requests, like this:

flask run --host=0.0.0.0

Question 3

# Problem code 
TypeError: Rule.__init__() got an unexpected keyword argument 'method'

The method in the decorator of the view function is missing s, as follows:

# Error code 
user_bp.route( '/settings/data' , method=[ 'GET' , 'POST' ])

Question 4

AssertionError: View function mapping is overwriting an existing endpoint function: blog.change_theme

The function name is repeated, there are two change_theme functions in the file

Question 5

TypeError: The view function for 'xxx' did not return a valid response. The function either returned None or ended without a return statement.

The return position in the view function is wrong, usually the redundant tab key causes the function to lack a return statement

Question 6

# Error code 
TypeError: 'bool' object is  not callable
 # Error 
if current_user.is_admin()

Note the difference between properties and methods, properties do not need parentheses, and methods require parentheses

Question 7

Method Not Allowed.The method is not allowed for the requested URL.

There is only a post method in the view function and no request method, so direct access will report an error

Question 8

# error code
RuntimeError
RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.

The request object in flask can only be used under the view function, and an error will be reported when used elsewhere

Question 9

sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '@rm-bp1o019zha4dfz18h2o.mysql.rds.aliyuncs.com' ([Errno 11003] getaddrinfo failed)")

Because there are special characters in the password, it is impossible to connect to the database normally. Generally, the password contains the @ character, which can be solved by changing the password.

Question 10

sqlalchemy.exc.InvalidRequestError: Mapper 'mapped class User->user' has no property 'role'

The role attribute is not added to the User model

Question 11

sqlalchemy.exc.InvalidRequestError: Could not locate a property which relates instances of class 'Collect' to instances of class 'User'

There is no connection between the Collect model and the User model

Question 12

# Error code 
SAWarning: Attribute 'BSCV
A' on class <class 'mw.models.Cornea'> appears to be a non-schema 'sqlalchemy.sql.column()' object; this won't be part of the declarative mapping
BSCVA = db.column(db.DECIMAL(2, 1))

The first letter of the column is not capitalized, resulting in a database table declaration error

Question 13

# Error code 
AttributeError: 'User' object has no attribute 'translate'

When the data is submitted to the database, the type is wrong, as shown in the code. At this time, it is necessary to check whether all data types submitted to the User table are consistent with the declaration

Question 14

sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship User.comments - there
 are no foreign keys linking these tables.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, o
r specify a 'primaryjoin' expression.

If there is an error in the establishment of the relationship, you can check the relationship of the target table one by one to check the error.

Question 15

smtplib.SMTPServerDisconnected: please run connect() first

An error is reported when using the smtp service to send emails. The account and password involved in the service are all stored in the .env file. [Flask] will automatically read the parameters in the .env file, but the file must be placed in the project root directory, otherwise it will be unreadable due to report an error

Question 16

self.port = int(port)
ValueError: invalid literal for int() with base 10: 'None'

SQLAlchemy represents an engine’s source as a URI along with optional string parameters that set engine options. The URI is of the form:

return self.registry[key]
KeyError: 140581010807680
dialect+driver://username:password@host:port/database

The reason for the above error is that the program did not read the port in the URI. At this time, you need to check the environment variable configuration file. If the configuration is accurate but still cannot read the port value in the configuration file, pay attention to the following problems:

During development, because python-dotenv is installed, Flask will automatically import the environment variables stored in the .flaskenv or .env file when starting the development server with the flask run command. In the production environment, we need to use a higher-performance production server, so we can no longer use this command to start the program. At this time, we need to manually import the environment variables.

We should import environment variable operations as early as possible to ensure that the code in the program that obtains environment variables works properly, so the best place to import is in the wsgi.py script, followed by the top of the package construction file. In the wsgi.py script, we manually import the environment variables set in the .env file using the load_dotenv() function provided by python-dotenv as follows:

from dotenv import load_dotenv

dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(dotenv_path):
    load_dotenv(dotenv_path)

from bluelog import create_app
app = create_app('production')

The order in the above code is very important. The statement for manually importing environment variables must be at the top, otherwise some environment variables will not be read and the program will crash.

Question 17

AttributeError: 'int' object has no attribute '_sa_instance_state'

When creating an object assignment for a Flask database foreign key field, you need to assign the object, not the object’s id or other separate fields.

Leave a Comment

Your email address will not be published. Required fields are marked *