http请求与相映 c++ curl及相应python代码

curl

#include <app/fusion/curl_post.hpp>
#include <terrace/thirdparty/spdlog/spdlog.h>
using namespace std;
Curl::Curl()
{
    curl _global_init(CURL_GLOBAL_ALL) ;
    curl_ = curl_easy_init();
}
Curl::~Curl()
{
    curl _global_cleanup();
}
bool Curl::post(string &addr, string &json_str, vector<string> &image jpeg, string &encoded_video_data)
{
    //CURL *curl = curl_easy_init();
    CURLcode res;
    struct curl_httppost *formpost = NULL;
    struct curl_httppost *lastptr = NULL;
    struct curl_slist *headerlist = NULL;
    static const char buf[] = "Expect:";
    if (NULL != curl_) {
        curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "json_info",CURLFORM_COPYCONTENTS,json_str.c_str(),CURLFORM_END);
        if (image_jpeg.size() == 1) {
            curl_formadd(&formpost, &lastptr,
            CURLFORM_COPYNAME, "image",
            CURLFORM_BUFFER, "image.jpg",
            CURLFORM_BUFFERPTR, image_jpeg[0].c_str(),
            CURLFORM_BUFFERLENGTH, image_jpeg[0].size(),
            CURLFORM_END);
        } else {
            for (int i = 0; i < image jpeg.size(); i++) {
            string image_name = "image" + to_string(i);
            string image_buffer = "image" + to_string(i) + ".jpg";
            curl_formadd(&formpost, &lastptr,
            CURLFORM_COPYNAME, image_name.c_str(),
            CURLFORM_BUFFER, image_buffer.c_str(),
            CURLFORM_BUFFERPTR, image _jpeg[i].c_str(),
            CURLFORM_BUFFERLENGTH, image jpeg[i].size(),
            CURLFORM_END);
            }
    

        }
        if (!encoded_video_data.empty())
        {
            curl_formadd(&formpost, &lastptr,
            CURLFORM_COPYNAME, "video",
            CURLFORM_BUFFER, "video.mp4",
            CURLFORM_BUFFERPTR, encoded_video _data.c_str(),
            CURLFORM_BUFFERLENGTH, encoded_video_data.size(),
            CURLFORM_END) ;
        }
        headerlist = curl_slist_append(headerlist, buf);
        curl_easy_setopt(curl_, CURLOPT_URL, addr.c_str());
        curl_easy_setopt(curl_, CURLOPT_NOSIGNAL, 1L);
        curl_easy_setopt(curl_, CURLOPT_TIMEOUT, 10L);
        curl_easy_setopt(curl_, CURLOPT_CONNECTTIMEOUT, 5L);
        curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, headerlist);
        curl_easy_setopt(curl_, CURLOPT_HTTPPOST, formpost);
        auto time = chrono: :high_resolution_clock: :now();
        res = curl _easy_perform(curl_);
        auto time_elapsed = chrono: :duration_cast<chrono: :microseconds>(chrono: :high_resolution_clock::now() - time) .count();
        float time_seconds = time_elapsed / 1000000.f;
        spdlog:: debug("post time: {}", time_seconds);
// if (res != CURLE_OK)
        if (res != 0)
        {
        spdlog::error("post back failed: {}", curl_easy strerror(res));
        }
        curl_formfree(formpost) ;
        curl_slist_free_all(headerlist) ;
    }
// curl_easy_cleanup(curl);
return true;
}
int Curl::post(const string &addr, const string &info, const string *resp) {
    CURLcode res;
    struct curl_httppost *formpost = NULL;
    struct curl_httppost *lastptr = NULL;
    struct curl_slist *headerlist = NULL;
    static const char buf[] = "Expect:";
    if (NULL != curl_) {
        curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "info", CURLFORM_COPYCONTENTS, info.c_str(), CURLFORM_END);
        headerlist = curl_slist_append(headerlist, buf);
        // curl_easy_setopt(curl_, CURLOPT_SSLVERSION, 3); //iRTESSLIRA ,1-31)
        curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, false);
        curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, false); // true
        curl_easy_setopt(curl_, CURLOPT_URL, (char *)addr.c_str());
        curl_easy_setopt(curl_, CURLOPT_TIMEOUT, 5);
        curl_easy_setopt(curl_, CURLOPT_CONNECTTIMEOUT_MS, 5000);
        curl_easy_setopt(curl_, CURLOPT_NOSIGNAL, 1);
        curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, headerlist);
        curl_easy_setopt(curl_, CURLOPT_HTTPPOST, formpost) ;
        curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, write_data_json) ;
        curl_easy_setopt(curl_, CURLOPT_WRITEDATA, (void *)resp);
        auto time = chrono: :high resolution_clock: :now();
        res = curl_easy_perform(curl_);
        auto time_elapsed = chrono: :duration_cast<chrono: :microseconds>(chrono: :high_resolution_clock: :now({) - time) .count();
        float time_seconds = time_elapsed / 1000000.f;
        if (res != CURLE_OK) {
        spdlog::error("post back failed: {}, post time {}s", curl_easy_strerror(res), time_seconds);
        return false;
        }
        curl_formfree(formpost) ;
        curl slist_free_all(headerlist);
    }
    return true;
}
size_t write_data_json(void *ptr, size_t size, size_t nmemb, void *stream)
{
// string data((const char *)ptr, (size_t)size * nmemb);
// *((stringstream *)stream) << data << endl;
// return size * nmemb;
    string *str = (string *)stream;
    (*str).append((char *)ptr, size * nmemb);
    return size * nmemb;
}   

#include <unistd.h>

#include <set>

#include <string.h>

#include <time.h>

#include <curl/curl.h>

#include <string>

#include <stdio.h>

#include <vector>

#include <iostream>

#include <fstream>

#include <sstream>

#include <chrono>

class Curl

{

public:
Curl();
~Curl();
bool post(std::string &addr, std::string &json_str, std::vector<std::string> &image_jpeg, std::string &encoded_video_data);
int post(const std::string &addr, const std::string &info, const std::string *resp);
int device_id_;
CURL *curl ;

};

size_t write_data_json(void *ptr, size_t size, size_t nmemb, void *stream);

python


import os
import json
from traceback import srint_tk
import requests
import base64
import multiprocessing
import shutil
import pandas as pd
import numpy as rp
from tqdm import tqdm
testimgs_addr = "http://127.0.@.1:8810/api/iqa_image_process"
# testimgs_addr = "http://127.0.0.1:8803/api/images/process”
my_task={}
# path="/data2/iqa/1/232/"
path="/data2/iqa/baitian"
def post_images(pic_Lists):
    global path
    for pic in tqdm(pic_Lists):
# for pic in pic_Lists:
# pic = pic_Lists[i]
        pic_path=os.path. join(path, pic)
        # print(pic_path)
        img=open(pic_path, "rb").read()
        my_files = {'image_content' : ('image.jpg',img )}
        my_task["device_id"] ="135456"
        r = requests.post(testimgs_addr,files=my_files,data= my_task)
        res_join = json.loads(r.text)
mpic_Lists=os. listdir(path)
img_len=int(len(mpic_Lists)/5)
test_parm=[mpic_Lists[:img_len],mpic_Lists[img_len:2*img_len],mpic_Lists[2*img_len:3*img_len],mpic_Lists[3*img_len:4*img_len],mpic_Lists[4*img_len:]]
pool=multiprocessing.Pool(5)
pool ,map(post_images, test_parm)
pool.close()
pool. join()
from email.mime import image
import tornado.ioloop
import tornado.web
import json
import cv2
import numpy as np
import time
import os,uwuid
import hashlib
a= 0
def mkdir(path):
    if not (os.path.exists(path)):
        os.makedirs(path)
def get_img(pic, image_name):
    if len(pic) > 2000:
        tmp = np.asarray(bytearray(pic), dtype="uint8")
        img = cv2.imdecode(tmp, cv2.IMREAD_COLOR)
        cv2.imwrite(image_name, img)
    else:
        print("pic error")
class MainHandler (tornado. web. RequestHandler):
    def get(self):
        self.write("Hello, world")
    def post(self):
        global a
        body = self.request.body
        print("len{body): ", len(body))
        print("len(files): ", len(self.request.files))
        # post_data = self.request.arguments
        # post_data = {x: post_data.get(x)[@].decode(“utf-8") for x in post_data.keys{)}
        # if not post_data:
        # post_data = self.request.body.decode(‘utf-8')
        # post_data = json. loads{post_data)
        # print{post_data)
        json_info = self.get_body_arguments("json_info")[0]
        # print("json_info: “, json.dumps(json_info ,sort_keys=True,indent= 4, separators=(",",:":")))
        j = json. loads(json_info)
        #dir_name = j["device_id"]
        localtime = time. localtime(time.time())
        #dir_ = str(localtime.tm_mday)+"_"+str(localtime.tm_hour)+"_"+str(localtime.tm_min)
        dir_ = str(localtime. tm_mday)+"_"+str(localtime.tm_hour)
        save_path = os.path.join(dir_, j["device_id"])
        if not os.path.exists(save_path):
            mkdir (save_path)
        if "video_quality" in j and j["video_quality"]== -1:
            randomByteArray = bytearray(os.urandom( 126680) )
            flatNumpyArray = np.array(randomByteArray)
            bgrImage = flatNumpyArray.reshape(100,400, 3)
            image_name=str(a)+"_-1. jpg"
            cv2.imwrite(os.path.join(save_path, image_name),bgrImage)
        
        else:
            if "image_quality" in j:
            # with open(save_path + "/json_info.txt","w") as f:
            # f.write(json.dumps({j, indent=4))
            # image_save_dict={}
            # for image_dict in j["image_quality"]:
            # tmp_dict = {}
            # tmp_dict["image_quality”] = str(image_dict["image_quality"])
            # tmp_dict[“cla_pro"] = str(round(image_dict[“classification_prob"],3))
            # save_name = “image” + str(image_dict["image_num"])
            # image_save_dict[save_name] = tmp_dict
                for k, v in self.request.files.items():
                    if "image" in k:
                    # save_img dict[j["device_id"]]= str{a)
                        image = v[0]["body"]
                        image_name=str(a)+"_"+str(j["image_quality"])+"_"+str(round(j["classification_prob"],3))+".jpg"
                        get_img(image, os.path.join(save_path, image name) )
                        a =a+1
                    elif "video" in k:
                        video = v[0]["body"]
                        if j["save_video"]:
                            if len(video) > 2000:
                                with open(save_path + "/video.mp4","wb") as f:
                                    f.write(video)
                            else:
                                print("save_video error: ", video)
def make_app():
    return tornado.web.Application([
    (r"/", MainHandler),
    ])
if __name__ == "main ":
    app = make_app()
    app. listen(8090)
    tornado.ioloop.IOLoop.current().start()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小涵涵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值