欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

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

发布时间:2025/3/15 编程问答 37 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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.

如图:


我也是醉了,琢磨了半天。

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

二、解决办法

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

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


去掉括号就成功解决此问题

# coding:utf-8import 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.argsname = littledata.get('username')print(name)# return "Hello,thi s is index!"# 响应为html格式# return "<p style ='color:green'>Hello,thi s is index!</p>"# 如果返回加载一个文件return render_template('login.html')# 3.运行服务器,如果不指定端口,就会默认端口5000 app.run(port=8003)

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

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

总结

以上是生活随笔为你收集整理的RuntimeError: Working outside of request context. This typically means that you attempted to use fun的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。