最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

如何用Django處理gzip數(shù)據(jù)流

 更新時(shí)間:2021年01月29日 16:30:40   作者:ysj  
這篇文章主要介紹了如何用Django處理gzip數(shù)據(jù)流,幫助大家更好的理解和使用django框架,感興趣的朋友可以了解下

最近在工作中遇到一個(gè)需求,就是要開一個(gè)接口來接收供應(yīng)商推送的數(shù)據(jù)。項(xiàng)目采用的python的django框架,我是想也沒想,就直接一梭哈,寫出了如下代碼:

class XXDataPushView(APIView):
  """
  接收xx數(shù)據(jù)推送
  """
		# ...
  @white_list_required
  def post(self, request, **kwargs):
    req_data = request.data or {}
				# ...

但隨后,發(fā)現(xiàn)每日數(shù)據(jù)并沒有任何變化,質(zhì)問供應(yīng)商是否沒有做推送,在忽悠我們。然后對(duì)方給的答復(fù)是,他們推送的是gzip壓縮的數(shù)據(jù)流,接收端需要主動(dòng)進(jìn)行解壓。此前從沒有處理過這種壓縮的數(shù)據(jù),對(duì)方具體如何做的推送對(duì)我來說也是一個(gè)黑盒。

因此,我要求對(duì)方給一個(gè)推送的簡(jiǎn)單示例,沒想到對(duì)方不講武德,仍過來一段沒法單獨(dú)運(yùn)行的java代碼:

private byte[] compress(JSONObject body) {
  try {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(out);
    gzip.write(body.toString().getBytes());
    gzip.close();
    return out.toByteArray();
  } catch (Exception e) {
    logger.error("Compress data failed with error: " + e.getMessage()).commit();
  }
  return JSON.toJSONString(body).getBytes();
}

public void post(JSONObject body, String url, FutureCallback<HttpResponse> callback) {
  RequestBuilder requestBuilder = RequestBuilder.post(url);
  requestBuilder.addHeader("Content-Type", "application/json; charset=UTF-8");
  requestBuilder.addHeader("Content-Encoding", "gzip");

  byte[] compressData = compress(body);

  int timeout = (int) Math.max(((float)compressData.length) / 5000000, 5000);

  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
  requestConfigBuilder.setSocketTimeout(timeout).setConnectTimeout(timeout);

  requestBuilder.setEntity(new ByteArrayEntity(compressData));

  requestBuilder.setConfig(requestConfigBuilder.build());

  excuteRequest(requestBuilder, callback);
}

private void excuteRequest(RequestBuilder requestBuilder, FutureCallback<HttpResponse> callback) {
  HttpUriRequest request = requestBuilder.build();
  httpClient.execute(request, new FutureCallback<HttpResponse>() {
    @Override
    public void completed(HttpResponse httpResponse) {
      try {
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        if (callback != null) {
          if (responseCode == 200) {
            callback.completed(httpResponse);
          } else {
            callback.failed(new Exception("Status code is not 200"));
          }
        }
      } catch (Exception e) {
        logger.error("Get error on " + requestBuilder.getMethod() + " " + requestBuilder.getUri() + ": " + e.getMessage()).commit();
        if (callback != null) {
          callback.failed(e);
        }
      }

      EntityUtils.consumeQuietly(httpResponse.getEntity());
    }

    @Override
    public void failed(Exception e) {
      logger.error("Get error on " + requestBuilder.getMethod() + " " + requestBuilder.getUri() + ": " + e.getMessage()).commit();
      if (callback != null) {
        callback.failed(e);
      }
    }

    @Override
    public void cancelled() {
      logger.error("Request cancelled on " + requestBuilder.getMethod() + " " + requestBuilder.getUri()).commit();
      if (callback != null) {
        callback.cancelled();
      }
    }
  });
}

從上述代碼可以看出,對(duì)方將json數(shù)據(jù)壓縮為了gzip數(shù)據(jù)流stream。于是搜索django的文檔,只有這段關(guān)于gzip處理的裝飾器描述:

django.views.decorators.gzip 里的裝飾器控制基于每個(gè)視圖的內(nèi)容壓縮。

  • gzip_page()

如果瀏覽器允許 gzip 壓縮,那么這個(gè)裝飾器將壓縮內(nèi)容。它相應(yīng)的設(shè)置了 Vary 頭部,這樣緩存將基于 Accept-Encoding 頭進(jìn)行存儲(chǔ)。

但是,這個(gè)裝飾器只是壓縮請(qǐng)求響應(yīng)至瀏覽器的內(nèi)容,我們目前的需求是解壓縮接收的數(shù)據(jù)。這不是我們想要的。

幸運(yùn)的是,在flask中有一個(gè)擴(kuò)展叫flask-inflate,安裝了此擴(kuò)展會(huì)自動(dòng)對(duì)請(qǐng)求來的數(shù)據(jù)做解壓操作。查看該擴(kuò)展的具體代碼處理:

# flask_inflate.py
import gzip
from flask import request

GZIP_CONTENT_ENCODING = 'gzip'


class Inflate(object):
  def __init__(self, app=None):
    if app is not None:
      self.init_app(app)

  @staticmethod
  def init_app(app):
    app.before_request(_inflate_gzipped_content)


def inflate(func):
  """
  A decorator to inflate content of a single view function
  """
  def wrapper(*args, **kwargs):
    _inflate_gzipped_content()
    return func(*args, **kwargs)

  return wrapper


def _inflate_gzipped_content():
  content_encoding = getattr(request, 'content_encoding', None)

  if content_encoding != GZIP_CONTENT_ENCODING:
    return

  # We don't want to read the whole stream at this point.
  # Setting request.environ['wsgi.input'] to the gzipped stream is also not an option because
  # when the request is not chunked, flask's get_data will return a limited stream containing the gzip stream
  # and will limit the gzip stream to the compressed length. This is not good, as we want to read the
  # uncompressed stream, which is obviously longer.
  request.stream = gzip.GzipFile(fileobj=request.stream)

上述代碼的核心是:

 request.stream = gzip.GzipFile(fileobj=request.stream)

于是,在django中可以如下處理:

class XXDataPushView(APIView):
  """
  接收xx數(shù)據(jù)推送
  """
		# ...
  @white_list_required
  def post(self, request, **kwargs):
    content_encoding = request.META.get("HTTP_CONTENT_ENCODING", "")
    if content_encoding != "gzip":
      req_data = request.data or {}
    else:
      gzip_f = gzip.GzipFile(fileobj=request.stream)
      data = gzip_f.read().decode(encoding="utf-8")
      req_data = json.loads(data)
    # ... handle req_data

ok, 問題完美解決。還可以用如下方式測(cè)試請(qǐng)求:

import gzip
import requests
import json

data = {}

data = json.dumps(data).encode("utf-8")
data = gzip.compress(data)

resp = requests.post("http://localhost:8760/push_data/",data=data,headers={"Content-Encoding": "gzip", "Content-Type":"application/json;charset=utf-8"})

print(resp.json())

以上就是如何用Django處理gzip數(shù)據(jù)流的詳細(xì)內(nèi)容,更多關(guān)于Django處理gzip數(shù)據(jù)流的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python使用matplotlib庫(kù)生成隨機(jī)漫步圖

    python使用matplotlib庫(kù)生成隨機(jī)漫步圖

    這篇文章主要為大家詳細(xì)介紹了使用Python的matplotlib庫(kù)生成隨機(jī)漫步圖,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-08-08
  • flask中主動(dòng)拋出異常及統(tǒng)一異常處理代碼示例

    flask中主動(dòng)拋出異常及統(tǒng)一異常處理代碼示例

    這篇文章主要介紹了flask中主動(dòng)拋出異常及統(tǒng)一異常處理代碼示例,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2018-01-01
  • 利用Python實(shí)現(xiàn)簡(jiǎn)單的相似圖片搜索的教程

    利用Python實(shí)現(xiàn)簡(jiǎn)單的相似圖片搜索的教程

    這篇文章主要介紹了利用Python實(shí)現(xiàn)簡(jiǎn)單的相似圖片搜索的教程,文中的示例主要在一個(gè)圖片指紋數(shù)據(jù)庫(kù)中實(shí)現(xiàn),需要的朋友可以參考下
    2015-04-04
  • pandas如何計(jì)算移動(dòng)平均值

    pandas如何計(jì)算移動(dòng)平均值

    在處理金融數(shù)據(jù)分析時(shí),常需計(jì)算移動(dòng)平均值。遇到數(shù)據(jù)不足導(dǎo)致結(jié)果為NAN問題,可使用pandas中rolling函數(shù)的min_periods參數(shù)。設(shè)置min_periods=1即可解決,它允許窗口中的非空觀測(cè)值少于窗口大小時(shí)也能計(jì)算均值,確保數(shù)據(jù)不足時(shí)也能得出結(jié)果
    2024-09-09
  • python Django模板的使用方法(圖文)

    python Django模板的使用方法(圖文)

    模板通常用于產(chǎn)生HTML,但是Django的模板也能產(chǎn)生任何基于文本格式的文檔。
    2013-11-11
  • Python中一個(gè)for循環(huán)循環(huán)多個(gè)變量的示例

    Python中一個(gè)for循環(huán)循環(huán)多個(gè)變量的示例

    今天小編就為大家分享一篇Python中一個(gè)for循環(huán)循環(huán)多個(gè)變量的示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • Python Flask框架使用介紹

    Python Flask框架使用介紹

    今天來給大家說一個(gè)Python的輕量級(jí)web開發(fā)框架——Flask,為什么要推薦它呢?當(dāng)然是因?yàn)樗鼔蜉p量級(jí)了,開發(fā)迅速是它的特點(diǎn),當(dāng)然它也有缺點(diǎn),不過這里不說,因?yàn)榧扔盟终f它差感覺不好
    2022-08-08
  • Python assert關(guān)鍵字原理及實(shí)例解析

    Python assert關(guān)鍵字原理及實(shí)例解析

    這篇文章主要介紹了Python assert關(guān)鍵字原理及實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • python有序查找算法 二分法實(shí)例解析

    python有序查找算法 二分法實(shí)例解析

    這篇文章主要介紹了python有序查找算法 二分法實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-02-02
  • Python 線程池模塊之多線程操作代碼

    Python 線程池模塊之多線程操作代碼

    最近在做一個(gè)爬蟲相關(guān)的項(xiàng)目,單線程的整站爬蟲,耗時(shí)真的不是一般的巨大,運(yùn)行一次也是心累,所以,要想實(shí)現(xiàn)整站爬蟲,多線程是不可避免的,那么python多線程又應(yīng)該怎樣實(shí)現(xiàn)呢?今天小編給大家分享下實(shí)現(xiàn)代碼,感興趣的朋友一起看看吧
    2021-05-05

最新評(píng)論

遂平县| 海原县| 商城县| 儋州市| 广宗县| 和顺县| 威远县| 铜鼓县| 黔西| 闵行区| 正镶白旗| 炎陵县| 临江市| 樟树市| 株洲市| 开江县| 杭锦后旗| 元朗区| 建平县| 韩城市| 墨玉县| 苍溪县| 金阳县| 怀化市| 湄潭县| 三台县| 海伦市| 白沙| 大冶市| 武义县| 靖江市| 定西市| 垫江县| 梁山县| 长阳| 福海县| 灵台县| 普安县| 东乡| 邛崃市| 都兰县|