RuntimeError: Working outside of request context. This typically means that you attempted to use fun

菜吃多了醉了

  • 一、报错情况
  • 二、解决办法

一、报错情况

我在写装饰器的时候运行报错:

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.

如图:

RuntimeError: Working outside of request context. This typically means that you attempted to use fun_第1张图片
我也是醉了,琢磨了半天。

https://blog.csdn.net/hanhanwanghaha宝藏女孩 欢迎您的关注!
欢迎关注微信公众号:宝藏女孩的成长日记
让这个可爱的宝藏女孩在努力的道路上与你一起同行!
如有转载,请注明出处(如不注明,盗者必究)

二、解决办法

装饰器第一个参数是原函数,如果装饰器可以接收参数的话,那么后面可以跟别的参数,否则就只有一个参数。所以,判断装饰器接收的参数,如果只有一个并且第一个参数是可调用的,那么就是一个无参数的装饰器(不需要加括号)。如果还有别的参数,就返回一个生成装饰器的函数。

在检查代码的时候我就发现了一个经常犯的错误,就是不用加()

RuntimeError: Working outside of request context. This typically means that you attempted to use fun_第2张图片
去掉括号就成功解决此问题

# coding:utf-8

import time
# 请求与响应
from flask import Flask, request, render_template

# 1.初始化application
app = Flask(__name__,
            template_folder="bbb",
            static_url_path="/ooo",
            static_folder="ooo"
            )


# 装饰器 打印时间
def log_time(f):
    def decorator(*args, **kw):
        print(f'{time.time()}')
        return f(*args, **kw)
    return decorator


# 2.添加路由 视图函数(view function)
@app.route("/login")
@app.route("/cute")
@app.route("/")
@log_time
def index():
    # 参数的获取:
    littledata = request.args
    name = littledata.get('username')
    print(name)
    # return "Hello,thi  s is index!"

    # 响应为html格式
    # return "

Hello,thi s is index!

"
# 如果返回加载一个文件 return render_template('login.html') # 3.运行服务器,如果不指定端口,就会默认端口5000 app.run(port=8003)

https://blog.csdn.net/hanhanwanghaha宝藏女孩 欢迎您的关注!
欢迎关注微信公众号:宝藏女孩的成长日记
让这个可爱的宝藏女孩在努力的道路上与你一起同行!
如有转载,请注明出处(如不注明,盗者必究)

温馨提示:千万不能吃饱了就干代码,休息会儿再敲,吃饱了会产生饭晕,你敲出来的不是代码,而是bug!!! 哈哈哈 fighting@everyone

你可能感兴趣的:(Python,python,flask,RuntimeError)