Django:应用级变量 [英] Django: app level variables

查看:107
本文介绍了Django:应用级变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个Django-rest-framework应用程序。它暴露了一些在MySQL数据库中进行一些获取/集合操作的API。



我有要求向另一台服务器发出HTTP请求,并将此响应与通常的响应一起提供。我试图使用自制的HTTP连接池来发出HTTP请求,而不是在每个请求上建立新的连接。



最适合的地方是什么应用级HTTP连接池对象?



我已经环顾四周了有多种解决方案都有一些缺点。这里有一些:


  1. 要在一个diff文件中创建一个单独的池类,但这不是一个很好的pythonic方式做事情对于为什么不使用单例设计模式有各种各样的讨论。



    此外,我不知道如何将池合并到一起? (:P)


  2. 将其保存在应用程序目录的 init .py中。这个问题如下:


    • 它应该只包含进口&

    • 单击测试代码将很难,因为导入将会在嘲笑之前发生,并且实际上会尝试点击API。


  3. 要使用会话,但是我猜想,如果是用户会话特定的东西,比如用户特定的号码等,则更有意义。
    $ b

    此外,该对象需要可序列化。我不知道HTTP连接池如何可以序列化。


  4. 为了在view.py中保持全局,但也不鼓励。

存储这样的应用程序/全局级变量的最佳位置是什么?

解决方案

可能的解决方案是实现自定义Django中间件,如 https://docs.djangoproject.com/ja/1.9/topics/http/middleware/



您可以初始化中间件的HTTP连接池 __ init __ 方法,它在第一个请求时仅被称为一次。然后,在 process_request process_response 期间启动HTTP请求,检查它是否已完成(或等待它),并将该响应附加到内部。


I've created a Django-rest-framework app. It exposes some API which does some get/set operations in the MySQL DB.

I have a requirement of making an HTTP request to another server and piggyback this response along with the usual response. I'm trying to use a self-made HTTP connection pool to make HTTP requests instead of making new connections on each request.

What is the most appropriate place to keep this app level HTTP connection pool object?

I've looked around for it & there are multiple solutions each with some cons. Here are some:

  1. To make a singleton class of the pool in a diff file, but this is not a good pythonic way to do things. There are various discussions over why not to use singleton design pattern.

    Also, I don't know how intelligent it would be to pool a pooler? (:P)

  2. To keep it in init.py of the app dir. The issue with that are as follows:
    • It should only contain imports & things related to that.
    • It will be difficult to unit test the code because the import would happen before mocking and it would actually try to hit the API.
  3. To use sessions, but I guess that makes more sense if it was something user session specific, like a user specific number, etc

    Also, the object needs to be serializable. I don't know how HTTP Connection pool can be serialized.

  4. To keep it global in views.py but that also is discouraged.

What is the best place to store such app/global level variables?

解决方案

A possible solution is to implement a custom Django middleware, as described in https://docs.djangoproject.com/ja/1.9/topics/http/middleware/.

You could initialize the HTTP connection pool in the middleware's __init__ method, which is only called once at the first request. Then, start the HTTP request during process_request and on process_response check it has finished (or wait for it) and append that response to the internal one.

这篇关于Django:应用级变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆