Tag Archives: flask

[Solved] Vite build & Flask Error: Failed to load module script. Strict MIME type checking is enforced

Vite build & Flask Error: Failed to load module script. Strict MIME type checking is enforced


Stack Overflow

questions

I have this HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link
        rel="stylesheet"
        href="../../../static/css/style.css"
        type="text/css" />
    <link
        rel="stylesheet"
        href="../../../static/css/user_header.css"
        type="text/css" />

    <!--suppress HtmlUnknownTarget -->
    <link rel="shortcut icon" href="/favicon.png">

    <script type="module" src="../../../static/js/node_connect.js" ></script>  <-- Error
    <script src="../../../static/lib/jquery.min.js"></script>
    <script src="../../../static/lib/selfserve.js"></script>   

</head>

The problem is node_connect.jsfile. Start the flash web tool locally (Python 3.7.2), and the console will report the following error when opening the page:

Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain".
Strict MIME type checking is enforced for module scripts per HTML spec.

Check Title:

Content-Type: text/plain; charset=utf-8

However, in production (when starting through gunicorn), it gives:

Content-Type: application/javascript; charset=utf-8

I guess the web server (APACHE) serves them in the production case, but another thing is that when testing other pages of the web tool, they all work and load JavaScript files correctly (even if their content type is text/plain text). However, the difference is that I notice that in the type.

This applies to my situation:

<script src="../../static/js/translator/library/materialize.js"></script>

Or this:

<script type="application/javascript" src="../../static/js/translator/library/materialize.js"></script>

Of course, I tried this for the problematic JavaScript . File and received the following error (which means it is now loaded):

Uncaught SyntaxError: Cannot use import statement outside a module

According to my research, this basically means that I need to set the type to module (but this will make the browser reject .js files).

Who can help me solve this problem?

best answer:

The problem is caused by flash how to guess the content type of each static file
Import mimetypes from flash and call mimeType, encoding = mimetypes guess_type (download_name) this module creates a database of known MIME types from multiple sources and uses it to return MIME types
Linux and MacOS: look at the mimetypes.py files:

knownfiles = [
    "/etc/mime.types",
    "/etc/httpd/mime.types",                    # Mac OS X
    "/etc/httpd/conf/mime.types",               # Apache
    "/etc/apache/mime.types",                   # Apache 1
    "/etc/apache2/mime.types",                  # Apache 2
    "/usr/local/etc/httpd/conf/mime.types",
    "/usr/local/lib/netscape/mime.types",
    "/usr/local/etc/httpd/conf/mime.types",     # Apache 1.2
    "/usr/local/etc/mime.types",                # Apache 1.3
    ]

But in windows, it will look in the registry:

with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '') as hkcr:
    for subkeyname in enum_types(hkcr):
        try:
            with _winreg.OpenKey(hkcr, subkeyname) as subkey:
                # Only check file extensions
                if not subkeyname.startswith("."):
                    continue
                # raises OSError if no 'Content Type' value
                mimetype, datatype = _winreg.QueryValueEx(
                    subkey, 'Content Type')
                if datatype != _winreg.REG_SZ:
                    continue
                self.add_type(mimetype, subkeyname, strict)

So to solve the problem, flask thinks JS file is actually a problem of text/plain , just open regedit and adjust this registry key to application/javaScript .

solutions for vite:

Find the registry value, double-click content type to change it to Application/JavaScript , and then restart the computer

if not, please see if your suffix is simple .js, if it is .1242342.js , must be changed to pure .JS suffix can take effect

In order to completely eradicate the disadvantages of modifying files, we can change the configuration file of vite , and modify the name of the output JS file by using the custom packaging option rollupOptions.

Reference: vite2 how to set the file name after packaging

Other configuration items of vite.config.js are shown on the official website. Click here to view more configuration items on the official website.

[Solved] Flask Application Context Error: RuntimeError: Working outside of application context.

[problem description]

The author encountered a classic error in flash. The error information is as follows:

[problem analysis]

application context is the application context of Flask, which contains variables such as app and g. When it is not convenient to operate app, we use current_app instead of app. current_app can only be accessed when processing requests, and I used current_app outside of processing requests, so an error was reported. Specifically, I used current_app in a custom tool class, ran the program, and could not get the application context when the program loaded the tool class, so the error was reported. The error code is as follows.

[problem-solving]

Since you can’t use current_app in the class property in the tool class, comment out the code and put it in the class method, and modify it as follows. The class method defined by me is used in the view, so the current_app is used in the view when processing the request, so no error will be reported and the problem is solved.

How to Solve no module fcntl Error in Windows

This library is specific to Linux, if you use this library in Windows system development, it will generate some errors, how to solve it?
Create a new fcntl.py file

DN_ACCESS = 1
DN_ATTRIB = 32
DN_CREATE = 4
DN_DELETE = 8
DN_MODIFY = 2
DN_MULTISHOT = 2147483648
DN_RENAME = 16

FASYNC = 8192

FD_CLOEXEC = 1

F_ADD_SEALS = 1033

F_DUPFD = 0

F_DUPFD_CLOEXEC = 1030

F_EXLCK = 4
F_GETFD = 1
F_GETFL = 3
F_GETLEASE = 1025
F_GETLK = 5
F_GETLK64 = 5
F_GETOWN = 9
F_GETSIG = 11

F_GET_SEALS = 1034

F_NOTIFY = 1026
F_RDLCK = 0

F_SEAL_GROW = 4
F_SEAL_SEAL = 1
F_SEAL_SHRINK = 2
F_SEAL_WRITE = 8

F_SETFD = 2
F_SETFL = 4
F_SETLEASE = 1024
F_SETLK = 6
F_SETLK64 = 6
F_SETLKW = 7
F_SETLKW64 = 7
F_SETOWN = 8
F_SETSIG = 10
F_SHLCK = 8
F_UNLCK = 2
F_WRLCK = 1

LOCK_EX = 2
LOCK_MAND = 32
LOCK_NB = 4
LOCK_READ = 64
LOCK_RW = 192
LOCK_SH = 1
LOCK_UN = 8
LOCK_WRITE = 128

def fcntl(fd, op, arg=0):
    return 0


def ioctl(fd, op, arg=0, mutable_flag=True):
    if mutable_flag:
        return 0
    else:
        return ""


def flock(fd, op):
    return


def lockf(fd, operation, length=0, start=0, whence=0):
    return

Just find your Python path and put it in

C:\Users\{Username}\AppData\Local\Programs\Python\Python38\Lib\fcntl.py

Done!

[Solved] flask db migrate execute error: ERROR [flask_migrate] Error: Can‘t locate revision identified by ‘8d1ad59dc71a‘

Recently, a new table has been added to the flash project, but an error is reported when executing flash DB migrate, as shown in the following figure:

Google around the Internet and finally know the problem:
although the migration directory in the project has been deleted, the version information has been saved in the database. Yes, this is the table – alembic_ version

So all you have to do is delete the version record of this table:

After deletion, execute flash DB migrate again, no error is reported, and the table is generated normally ~

[Solved] RuntimeError An attempt has been made to start a new process

1、 Exception 1: runtimeerror: an attempt has been made to start a new process

Reason: multiple processes need to run in the main function

Solution 1:

Add the main function and call it in main.

if __name__ == '__main__':
	main()

Solution 2:

num_workers changed to 0, single process loading

Ers changed to 0, single process loading

[Solved] flash initializate database error: Keyerror: ‘migrate’

from flask_sqlalchemy import SQLAlchemy

from flask_migrate import Migrate, migrate

def create_app(register_all=True, **kwargs):
    #Add this code under this method, add the database package and initialize,
     db=SQLAlchemy()
     db.init_app(app)
     #Import and initialize
    migrate=Migrate(db=db)
    migrate.init_app(app)
    return app

directory = current_ app.extensions[‘migrate’].directory

This sentence means that migrations are not generated

So you need to add migrate and initialize

DB needs to be added for initialization

AttributeError: module ‘time‘ has no attribute ‘clock‘ [How to Solve]

AttributeError: module ‘time’ has no attribute ‘clock’
Error Messages:

# `flask_sqlalchemy` Error:
File "D:\python38-flasky\lib\site-packages\sqlalchemy\util\compat.py", line 172, in <module>
    time_func = time.clock
AttributeError: module 'time' has no attribute 'clock'

reason:

Python 3.8 no longer supports time.clock, but it still contains this method when calling. There is a version problem.

Solution:

Use the replacement method: time.perf_Counter(), such as:

import time
if win32 or jython:
    # time_func = time.clock
    time_finc = time.perf_counter()
else:
    time_func = time.time

[Solved] Odrive gui Error: Do not use the development server in a productioun and supported version of the Socket

WARNING: Do not use the development server in a production environment. · Issue #446 · PaddlePaddle/VisualDL (github.com) https://github.com/PaddlePaddle/VisualDL/issues/446

The above is for reference

To set the parameters, then odrive_ The name of server depends on what the odrive GUI reports as an error, and it can be changed by comparison

set FLASK_APP=odrive_server
set FLASK_ENV=development

Then the version problem was solved by mistake

pip install --upgrade python-socketio==4.6.0

pip install --upgrade python-engineio==3.13.2

pip install --upgrade Flask-SocketIO==4.3.1

Error: While importing ‘run_app_dev‘, an ImportError was raised.

Problem description

Running a python flash project on a new machine causes the following problems:
error: while importing 'run_ app_ dev', an ImportError was raised.

resolvent

It is said on the Internet that it is a circular call problem, but this project can run on my laptop. I doubt whether it is the version of flash, because I directly installed the latest Flash. After uninstalling the latest flash, I installed 1.1.2 flash. This problem is solved

Flask Database Migration Error: ERROR [flask_migrate] Error: Can‘t locate revision identified by ‘a1c25fe0fc0e‘

Problem Description:

In flash web development, we will use the flash migrate library to migrate the database, so as to submit the changed database model we wrote in the program script to the database without deleting and rebuilding the database model
if we use Python manage.py DB init to create a migration warehouse, and then use the migrate or upgrade in flash migrate, the following two instructions:

python manage.py db migrate
python manage.py db upgrade

Error [flag_migrate] error: can’t locate revision identified by ‘a1c25fe0fc0e’ may appear. The identification number of ‘a1c25fe0fc0e’ corresponds to different database models! As shown in the figure:

resolvent:

The reason for the above error is that flash migrate cannot find the revision of “a1c25fe0fc0e” logo. We just need to indicate the missing logo number in the command
we can use the following commands in order in the shell command line window:

python app.py db revision --rev-id <Fill the prompt's identification number into this location, such as a1c25fe0fc0e above>
python app.py db migrate
python app.py db upgrade

Enter the following command to demonstrate:

then, the database migration succeeds

Finally, if there are deficiencies in the article, criticism and correction are welcome!

Flash cli encountered a keyerror “migrate” [How to Solve]

Flash management command-line tool. I use flash cli

Then, using any command related to flash DB will cause the problem of keyerror “migrate”

No solution was found on the Internet

Therefore, I started to think step by step and finally determined that the biggest problem without the migrate command was that when I executed the flash DB XX command, I didn’t find the corresponding app. The command line didn’t know which app I wanted to run, so I didn’t find the app associated with DB, that is, I didn’t find it

Migrate = migrate (APP = app, DB = dB), so an error is reported

Therefore, to use the flash command, you first need to declare flash_ APP

That is, enter in terminal

export FLASK_APP=The name of the app you want to run

=Do not leave a space before or after, otherwise bad assignment will be reported

Then enter flash DB migrate again and it will be normal

Gunicorn timeout error: [1] [critical] worker timeout [How to Solve]

1. Problem description

In a web project built with gunicorn + flash, because the machine learning model is used, the model needs to be loaded when requesting the interface for the first time. The model is loaded quickly when running locally, so it runs normally. The application is deployed to the server using docker (the model is mounted to the container through volume), The first request to load the model takes a long time, and the following errors are reported:

[2021-09-11 07:22:33 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:12)
[2021-09-11 07:22:35 +0000] [12] [INFO] Worker exiting (pid: 12)

Gunicorn ‘green Unicorn’ is a python WSGI HTTP server for UNIX. It is a pre forked worker model transplanted from Ruby’s Unicorn project. Gunicorn server is widely compatible with various web frameworks, with simple implementation, less use of server resources and quite fast speed.

2. Cause analysis

It can be seen from the error message that gunicorn’s worker process timed out, causing the process to exit and restart
refer to the official document of gunicorn and the description shown in the figure below:

3. Solution

From the documentation on the official website, we can know that the default timeout of gunicorn is 30s. If it exceeds 30s, the worker process will be killed and restarted.

Therefore, to solve this problem, you only need to set a large timeout: gunicorn to set the timeout

gunicorn -w 2 -b 0.0.0.0:4343  manage:app --timeout 120 

Add: -- timeout 120 to gunicorn’s startup command, indicating that the timeout is set to 120 seconds. Configure the timeout in the gunicorn. Conf.py configuration file of gunicorn

workers = 4  # Define the number of processes to be opened for processing requests at the same time, adjusted appropriately according to site traffic
worker_class = "gevent" # Use the gevent library to support asynchronous processing of requests and improve throughput
bind = "0.0.0.0:8500" # Listen to IP relaxation to facilitate communication between Dockers and between Dockers and hosts
timeout = 120 # Set the timeout to 120 seconds

For more configuration of the gunicorn. Conf.py file, see the official website