Tag Archives: flask

Python installs virtualenv through PIP and always reports an error: response.py“, line 438, in _error_catcher yield

G:\ESP32\esp-idf-release-v4.3>pip install virtualenv
Collecting virtualenv
  Downloading virtualenv-20.7.2-py2.py3-none-any.whl (5.3 MB)
     |█                               | 174 kB 4.5 kB/s eta 0:18:56ERROR: Exception:
Traceback (most recent call last):
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_vendor\urllib3\response.py", line 438, in _error_catcher
    yield
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_vendor\urllib3\response.py", line 519, in read
    data = self._fp.read(amt) if not fp_closed else b""
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 62, in read
    data = self.__fp.read(amt)
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\http\client.py", line 459, in read
    n = self.readinto(b)
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\http\client.py", line 503, in readinto
    n = self.fp.readinto(b)
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\socket.py", line 704, in readinto
    return self._sock.recv_into(b)
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\ssl.py", line 1241, in recv_into
    return self.read(nbytes, buffer)
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\ssl.py", line 1099, in read
    return self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_internal\cli\base_command.py", line 173, in _main
    status = self.run(options, args)
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_internal\cli\req_command.py", line 203, in wrapper
    return func(self, options, args)
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_internal\commands\install.py", line 315, in run
    requirement_set = resolver.resolve(
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 94, in resolve
    result = self._result = resolver.resolve(
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 472, in resolve
    state = resolution.resolve(requirements, max_rounds=max_rounds)
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 341, in resolve
    self._add_to_criteria(self.state.criteria, r, parent=None)
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 172, in _add_to_criteria
    if not criterion.candidates:
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_vendor\resolvelib\structs.py", line 151, in __bool__
    return bool(self._sequence)
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 140, in __bool__
    return any(self)
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 128, in <genexpr>
    return (c for c in iterator if id(c) not in self._incompatible_ids)
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 32, in _iter_built
    candidate = func()
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_internal\resolution\resolvelib\factory.py", line 204, in _make_candidate_from_link
    self._link_candidate_cache[link] = LinkCandidate(
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_internal\resolution\resolvelib\candidates.py", line 295, in __init__
    super().__init__(
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_internal\resolution\resolvelib\candidates.py", line 156, in __init__
    self.dist = self._prepare()
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_internal\resolution\resolvelib\candidates.py", line 227, in _prepare
    dist = self._prepare_distribution()
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_internal\resolution\resolvelib\candidates.py", line 305, in _prepare_distribution
    return self._factory.preparer.prepare_linked_requirement(
  File "g:\users\administrator\appdata\local\programs\python\python39\lib\site-packages\pip\_internal\operations\prepare.py", line 508, in prepare_linked_requirement
    return self._prepare_linked_requirement(req, parallel

Later, add the path of Python to the system variable

[Solved] Docker+uWSGI+Flask Error: ModuleNotFoundError: No module named ‘flask‘

Background

The docker + nginx + uwsgi + flask deployment environment has always been able to run well before. This time, the Python version of the basic image was upgraded from the original 3.6 to 3.8 , and the title was wrong.

docker + nginx + uwsgi + flask deployment can refer to this article

Problem analysis

Let’s take a look at the start log of docker:

Starting nginx: nginx.,
*** Starting uWSGI 2.0.18-debian (64bit) on [Tue Aug 17 02:21:46 2021] ***,
[uWSGI] getting INI configuration from uwsgi.ini,
compiled with version: 8.2.0 on 10 February 2019 02:42:46,
os: Linux-3.10.0-957.el7.x86_64 #1 SMP Thu Nov 8 23:39:32 UTC 2018,
nodename: 9c8cc3ffd4ed,
machine: x86_64,
pcre jit disabled,
detected number of CPU cores: 2,
clock source: unix,
current working directory: /code,
detected binary path: /usr/bin/uwsgi-core,
uWSGI running as root, you can use --uid/--gid/--chroot options,
chdir() to /code,
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** ,
*** WARNING: you are running uWSGI without its master process manager ***,
your memory page size is 4096 bytes,
detected max file descriptor number: 1048576,
lock engine: pthread robust mutexes,
thunder lock: disabled (you can enable it with --thunder-lock),
uwsgi socket 0 bound to TCP address :5000 fd 3,
uWSGI running as root, you can use --uid/--gid/--chroot options,
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** ,
Python version: 3.7.3 (default, Jan 22 2021, 20:04:44)  [GCC 8.3.0],
Python main interpreter initialized at 0x55fa4f5a8990,
uWSGI running as root, you can use --uid/--gid/--chroot options,
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** ,
python threads support enabled,
your server socket listen backlog is limited to 100 connections,
your mercy for graceful operations on workers is 60 seconds,
mapped 825016 bytes (805 KB) for 8 cores,
*** Operational MODE: preforking+threaded ***,
Traceback (most recent call last):,
  File "run.py", line 20, in <module>,
    from server import create_app,
  File "./server/__init__.py", line 14, in <module>,
    from flask import Flask,
unable to load app 0 (mountpoint='') (callable not found or import error),
*** no app loaded. going in full dynamic mode ***,
uWSGI running as root, you can use --uid/--gid/--chroot options,
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** ,
*** uWSGI is running in multiple interpreter mode ***,
spawned uWSGI worker 1 (pid: 21, cores: 2),
spawned uWSGI worker 2 (pid: 22, cores: 2),
spawned uWSGI worker 3 (pid: 23, cores: 2),
spawned uWSGI worker 4 (pid: 24, cores: 2)

It can be seen from this that an error is reported when quoting flash .

What causes this problem?

If the program does not find the python Library (flash) when running, it will report an error.

Here, we don’t care why he didn’t find it. Since he didn’t find it, we’ll take the initiative to tell him where to find it.

Solution

Modify uwsgi. Ini , and set the value of Python path to /usr/local/lib/Python 3.8/site packages/.

The content of the modified uwsgi. Ini file is:

[uwsgi]
chdir = /code
socket = :5000
pythonpath = /usr/local/lib/python3.8/site-packages/
wsgi-file = run.py
callable = app
chmod-socket = 666
plugins = python3
buffer-size = 65535
processes = 4
threads = 2

All right, problem solved.

[Solved] Can’t reconnect until invalid transaction is rolled back

The reason is that there is no call

session.rollback()

Solution:

@contextmanager
    def session_scope(self):
        self.db_engine = create_engine(self.db_config, pool_pre_ping=True) # echo=True if needed to see background SQL        
        Session = sessionmaker(bind=self.db_engine)
        session = Session()
        try:
            # this is where the "work" happens!
            yield session
            # always commit changes!
            session.commit()
        except:
            # if any kind of exception occurs, rollback transaction
            session.rollback()
            raise
        finally:
            session.close()

Another form:

        try:
        	......
            ......
            ......
            ......
        except Exception:
            import traceback
            traceback.print_exc()
            db.session.rollback()
            pass
        finally:
            db.session.close()
            pass

Microsoft Visual C++ 14.0 or greater is required. Get it with “Microsoft C++ Build Tools“

Alipay’s online payment function has recently been developed to download and pay the SDK package. The wrong presentation is as follows:
reported false prompts: Microsoft Visual C++ 14 or greater is required. Get it it ” https://visualstudio.microsoft.com/visual-cpp-build-tools/

Reason: python3 is compiled with VC + + 14, python27 is compiled with C + + 9, and the package to install python3 needs to be compiled with C + + 14 or above

Don’t panic for small scenes

That’s the thing above. Double click the installation. Do you think it’s over?

In case of no accident, most of the installation packages you download will finally prompt you: the installation package is missing or damaged
some netizens say that it can succeed with a ladder, and others say that it can’t succeed
I uploaded an offline version here. You can try

[Solved] Access to XMLHttpRequest at ‘http://127.0.0.1:5000/markdownlang/‘ from origin ‘null‘ has been bl

When AJAX is used, the above cross domain request error is reported (using Python flash to build the background)

Error code:

from flask import Flask,render_template
@app.route("/markdownlang/",methods=["post"])
def getMarkdownLang():
    return render_template('result.html')

Solution: add a response header on the server side to simply allow cross source.

from flask import Flask,render_template,make_response
@app.route("/markdownlang/",methods=["post"])
def getMarkdownLang():
    resp = make_response(render_template('result.html'))
    resp.headers['Access-Control-Allow-Origin'] = '*'   
    return resp

There are two other things that can go wrong:

    1. the requested path is not complete. Full path http://127.0.0.1:port number/file path. Cross source must have full path. The request mode has no corresponding response code on the server side. For example, the server should have a post response for a post request

Flask Request an extension before_request after_request errorhandler

Contents of articles

1 before_first_Request: execute 2 before the first request after the project starts_ Request: execute 3 after before each request_ Request: after each request, the request will not be executed in case of exception. 4 errorhandler: you can customize the status code of the listening response and handle it: 5 teardown_ Request: a function is bound after each request, and will be executed even if an exception is encountered in ‘non debug’ mode. 6 template_ Global (): global template label 7 template_ Filter: global template filter

1 before_ first_ Request: the first request is executed after the project is started

@app.before_first_request
def before_first_request():
    print('Executed on the first request')

2 before_ Request: executed before each request

@app.before_request
def before_request():
    print('execute before each request')
    # return 'direct return' # If one writes a return return value, then the other before_request will not be executed and the view will not be executed.

be careful:

You can write more than one. If one has written the return value, then the others are before_ The request does not execute, nor does the view.

3 after_ Request: after each request, the request will not be executed in case of exception

def after_request(result):
    print('Execute after each request, requests with exceptions will not be executed')
    # The result is a wrapped response object that needs to be returned or else an error is reported
    return result

4 errorhandler: you can customize the status code of the listening response and process it

@app.errorhandler(404)
def errorhandler(error):
    print(error)  # is the specific error message
    return 'The 404 page ran to Mars'

@app.errorhandler(500)
def errorhandler(error):
    print('errorhandlererror message')
    print(error)
    return 'Server internal error 500'

5 teardown_ Request: a function is bound after each request, which will be executed even if an exception is encountered in non debug mode.

@app.teardown_request
def terardown_reqquest(error):
    print('The view function will be executed after execution regardless of whether the view function has an error')
    print('debug cannot be True if you want this function to work')
    print('error is the specific error message')
    print(error)

6 template_ Global (): global template label

@app.template_global()
def add(a1, a2):
    return a1+a2
# {{add(1,2)}}

This can be used as a global label in the template. It can be called directly in the template

{{add(1,2)}}

7 template_ Filter: global template filter

@app.template_filter()
def add_filter(a1, a2, a3):
    return a1 + a2 + a3

This can be used as a global filter in the template. It can be called directly in the template. The calling method is the same as template_ The difference between global:

{{1|add_filter(2,3,4)}}

Advantages:

Global template tags and global template filters simplify the need to manually transfer a function to a template call

# app.py
```

def test(a1,a2):
    return a1+a2
@app.route('/')
def index():
    return render_template('index.html',test=test)

```

# index.html
```
{{test(22,22)}}

```

When writing a website, Vue + Flash prompts network error when visiting Vue page

Flash page is mounted at 127.0.0.1:8010
Vue page is mounted at 127.0.0.1:8080 (Axios. Defaults. Baseurl)=‘ http://127.0.0.1 :8010’)

After running, you can access port 8010, but when you access port 8080, you will be prompted with network error, and the security group port will be set to
after checking, it is found that port 8010 is forward to port 1527

guess that port 8010 is occupied
after a look, it is really

so you can directly modify the page port in app.py to 5000,
axios.defaults.baseURL = ‘ http://127.0.0.1 : 5000 ‘(or other non conflicting ports)

This time, you can directly access port 8080
it is found that using ‘127.0.0.1’ can still achieve public network page projection, but only using ‘0.0.0.0’ for flash

Solve the problem of flag error valueerror: View function did not return a response

Today, we use Python to implement the restful interface of Flask, and then call it wrong.

ValueError: View function did not return a response

The code is as follows:

@app.route('/xxxx/yyyy_zzzzz', methods=['POST', 'GET'])

def receive():

      param = request.json

      print(param)

The reason for the error is that the restful interface of flag must have a return value.

Therefore, modify the code to add the return value:

Add: return XXXX

For example:

@app.route('/xxxx/yyyy_zzzzz', methods=['POST', 'GET'])

def receive():

    try:

        if not request.json:

            return jsonify({'code': -1, 'message': 'request is not json'})

        param = request.json

        return jsonify({'code': 0, 'status': 'running'})

    except Exception as e:

        print(e)

        return jsonify({'code': -1, 'error_message':e})

 

Image proxy settings Flash + JavaScript

The article directories
Problem description idea specific implementation front end back end

Problem description
If is request http://www.example.com/image1.png picture originally, now ask for pictures, https://www.petal.social/image/www.example.com/image1.png you will need to do an image proxy
(request pictures to our own when the server request, then our HTTP server request images, the result of the HTTP in the way back to the web site of the HTTPS)
Train of thought
First, add an API locally for the front-end request that returns the modified image URL
The specific implementation
The front end
Original version:

showImage(url) {
    if (url.startsWith('http://')) {
        if (url.includes('qpic.cn') || url.includes('gtimg.cn')) {
            return url.replace('http://', 'https://')
        } else {
            return return 'https://demo.cloudimg.io/v7/' + url
        }
    } else {
        return url
    }
}

Image URL contains /, so in Flask is mistaken for routing calls, so you need to for the original URL with Base64 encryption
modify after:

import {Base64} from 'js-base64'
const BASE_URL = 'http://localhost:5000'
// const BASE_URL = 'https://www.petal.social'
showImage(url) {
    if (url.startsWith('http://')) {
        if (url.includes('qpic.cn') || url.includes('gtimg.cn')) {
            return url.replace('http://', 'https://')
        } else {
            return BASE_URL + '/api/v1/image/' + Base64.encode(url)
        }
    } else {
        return url
    }
}

The back-end

from flask_restplus import Namespace, Resource
from flask import request, make_response
from maintenance import check_maintenance, not_under_maintenance
import requests
from flask import Response, stream_with_context
import base64
image_api = Namespace('image', description='image related public interface')

@image_api.route('/<image_url>')
@image_api.param('image_url', 'The original image url')
class Image(Resource):
    @image_api.doc('get_image_url')
    @not_under_maintenance
    def get(self, image_url):
        check_maintenance()
        image_url = base64.b64decode(image_url)
        res = requests.get(image_url, stream = True)
        return Response(stream_with_context(res.iter_content(2048)), content_type = res.headers['content-type']) 

Error: Could not locate Flask application. You did not provide the FLASK_APP environment variable.

Problem description:

Error: Could not locate Flask application. You did not provide the FLASK_APP environment variable.

why
The FLASK_APP environment variable is not set
To solve
Under the win10
Powershell: $env:FLASK_APP="main.py" remember to replace main.py with your own filename
Py main. Py CMD: set FLASK_APP=flasky.py
As opposed to PowerShell… 😈

Error: can’t locate revision identified by ‘xxx’

Flask migration using sqlalchemy database error:

Error: Can't locate revision identified by 'xxxxxx'

error reason: the database version is wrong, maybe migrations file is changed, but the original database table is still used.

solution:

  1. delete migrations folder + alembic_version table in the database table, re-initialize the database and update;
  2. delete the entire database table, then you can directly do the database initialization update operation. (migrations folders can also be deleted, equivalent to recreating the database table, the original data will not exist)