mirror of https://github.com/ivanch/tcc.git
modificando json e protobuf
This commit is contained in:
parent
1eb02db473
commit
95a85be35d
|
@ -1,6 +1,5 @@
|
|||
using Microsoft.AspNetCore.Mvc;
|
||||
using ProtoBuf;
|
||||
using System.IO;
|
||||
using tcc_app.Models;
|
||||
|
||||
namespace TCC.Controllers
|
||||
{
|
||||
|
@ -24,25 +23,25 @@ namespace TCC.Controllers
|
|||
return Ok(sum);
|
||||
}
|
||||
|
||||
[HttpGet("json")]
|
||||
public async Task<IActionResult> GetJsonResponse()
|
||||
[HttpPost("json")]
|
||||
public async Task<IActionResult> PostJson([FromBody] PersonJson person)
|
||||
{
|
||||
return Ok(new { message = "Hello World!" });
|
||||
return Ok(person);
|
||||
}
|
||||
|
||||
[HttpPost("protobuf")]
|
||||
public async Task<IActionResult> PostProtobuf()
|
||||
{
|
||||
HelloWorld cliente;
|
||||
PersonProto person;
|
||||
byte[] response;
|
||||
using (var stream = Request.BodyReader.AsStream())
|
||||
{
|
||||
cliente = ProtoBuf.Serializer.Deserialize<HelloWorld>(stream);
|
||||
person = ProtoBuf.Serializer.Deserialize<PersonProto>(stream);
|
||||
}
|
||||
|
||||
using (var stream = new MemoryStream())
|
||||
{
|
||||
ProtoBuf.Serializer.Serialize(stream, cliente);
|
||||
ProtoBuf.Serializer.Serialize(stream, person);
|
||||
response = stream.ToArray();
|
||||
}
|
||||
|
||||
|
@ -51,11 +50,4 @@ namespace TCC.Controllers
|
|||
}
|
||||
}
|
||||
|
||||
[ProtoContract()]
|
||||
public class HelloWorld
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public string Message { get; set; }
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
namespace tcc_app.Models
|
||||
{
|
||||
public class PersonJson
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public int Age { get; set; }
|
||||
public List<string> Friends { get; set; }
|
||||
public string Email { get; set; }
|
||||
public string Phone { get; set; }
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
using ProtoBuf;
|
||||
|
||||
namespace tcc_app.Models
|
||||
{
|
||||
[ProtoContract()]
|
||||
public class PersonProto
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public string Name { get; set; }
|
||||
|
||||
[ProtoMember(2)]
|
||||
public int Age { get; set; }
|
||||
|
||||
[ProtoMember(3)]
|
||||
public List<string> Friends { get; set; }
|
||||
|
||||
[ProtoMember(4)]
|
||||
public string Email { get; set; }
|
||||
|
||||
[ProtoMember(5)]
|
||||
public string Phone { get; set; }
|
||||
}
|
||||
|
||||
}
|
|
@ -1,14 +1,31 @@
|
|||
use qstring::QString;
|
||||
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, HttpRequest, Result};
|
||||
use actix_files::NamedFile;
|
||||
// use actix_protobuf::{ProtoBuf, ProtoBufResponseBuilder as _};
|
||||
use actix_protobuf::*;
|
||||
use prost::Message;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Message)]
|
||||
pub struct HelloWorld {
|
||||
pub struct PersonProtobuf {
|
||||
#[prost(string, tag = "1")]
|
||||
pub message: String
|
||||
pub name: String,
|
||||
#[prost(int32, tag = "2")]
|
||||
pub age: i32,
|
||||
#[prost(string, repeated, tag = "3")]
|
||||
pub friends: Vec<String>,
|
||||
#[prost(string, tag = "4")]
|
||||
pub email: String,
|
||||
#[prost(string, tag = "5")]
|
||||
pub phone: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct PersonJson {
|
||||
pub name: String,
|
||||
pub age: i32,
|
||||
pub friends: Vec<String>,
|
||||
pub email: String,
|
||||
pub phone: String,
|
||||
}
|
||||
|
||||
#[get("/status/ok")]
|
||||
|
@ -37,20 +54,13 @@ async fn simulation_harmonic_progression(req: HttpRequest) -> impl Responder {
|
|||
HttpResponse::Ok().body(format!("{}", sum))
|
||||
}
|
||||
|
||||
#[get("/simulation/json")]
|
||||
async fn simulation_json() -> impl Responder {
|
||||
let body = serde_json::json!({
|
||||
"message": "Hello World!"
|
||||
});
|
||||
|
||||
HttpResponse::Ok()
|
||||
.json(body)
|
||||
#[post("/simulation/json")]
|
||||
async fn simulation_json(msg: web::Json<PersonJson>) -> impl Responder {
|
||||
HttpResponse::Ok().json(web::Json(msg))
|
||||
}
|
||||
|
||||
#[post("/simulation/protobuf")]
|
||||
async fn simulation_protobuf(msg: ProtoBuf<HelloWorld>) -> impl Responder {
|
||||
println!("model: {:?}", msg.0);
|
||||
|
||||
async fn simulation_protobuf(msg: ProtoBuf<PersonProtobuf>) -> impl Responder {
|
||||
HttpResponse::Ok().protobuf(msg.0)
|
||||
}
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
from flask import request, Blueprint, jsonify
|
||||
import helloworld_pb2
|
||||
import person_pb2
|
||||
|
||||
simulation_blueprint = Blueprint('simulation_blueprint', __name__)
|
||||
|
||||
|
@ -26,15 +26,16 @@ def return_ok():
|
|||
|
||||
return str(sum), 200
|
||||
|
||||
@simulation_blueprint.route('/simulation/json', methods=['GET'])
|
||||
@simulation_blueprint.route('/simulation/json', methods=['POST'])
|
||||
def return_helloworld():
|
||||
return simulation_controller.return_helloworld(), 200
|
||||
data = request.json
|
||||
return data, 200
|
||||
|
||||
@simulation_blueprint.route('/simulation/protobuf', methods=['POST'])
|
||||
def return_protobuf():
|
||||
bytes_data = request.data
|
||||
|
||||
helloworld = helloworld_pb2.MyObj()
|
||||
helloworld = person_pb2.Person()
|
||||
helloworld.ParseFromString(bytes_data)
|
||||
|
||||
return helloworld.SerializeToString(), 200
|
||||
|
|
|
@ -1,5 +0,0 @@
|
|||
syntax = "proto3";
|
||||
|
||||
message MyObj {
|
||||
string message = 1;
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
syntax = "proto3";
|
||||
|
||||
message Person {
|
||||
string name = 1;
|
||||
int32 age = 2;
|
||||
repeated string friends = 3;
|
||||
string email = 4;
|
||||
string phone = 5;
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
# source: helloworld.proto
|
||||
# source: person.proto
|
||||
# Protobuf Python Version: 4.25.0
|
||||
"""Generated protocol buffer code."""
|
||||
from google.protobuf import descriptor as _descriptor
|
||||
|
@ -14,13 +14,13 @@ _sym_db = _symbol_database.Default()
|
|||
|
||||
|
||||
|
||||
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10helloworld.proto\"\x18\n\x05MyObj\x12\x0f\n\x07message\x18\x01 \x01(\tb\x06proto3')
|
||||
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0cperson.proto\"R\n\x06Person\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0b\n\x03\x61ge\x18\x02 \x01(\x05\x12\x0f\n\x07\x66riends\x18\x03 \x03(\t\x12\r\n\x05\x65mail\x18\x04 \x01(\t\x12\r\n\x05phone\x18\x05 \x01(\tb\x06proto3')
|
||||
|
||||
_globals = globals()
|
||||
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
|
||||
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'helloworld_pb2', _globals)
|
||||
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'person_pb2', _globals)
|
||||
if _descriptor._USE_C_DESCRIPTORS == False:
|
||||
DESCRIPTOR._options = None
|
||||
_globals['_MYOBJ']._serialized_start=20
|
||||
_globals['_MYOBJ']._serialized_end=44
|
||||
_globals['_PERSON']._serialized_start=16
|
||||
_globals['_PERSON']._serialized_end=98
|
||||
# @@protoc_insertion_point(module_scope)
|
|
@ -1,14 +1,28 @@
|
|||
import helloworld_pb2
|
||||
import person_pb2
|
||||
|
||||
helloworld = helloworld_pb2.MyObj()
|
||||
helloworld.message = "Hello World!"
|
||||
person_proto = person_pb2.Person()
|
||||
person_proto.name = "John Doe"
|
||||
person_proto.age = 30
|
||||
person_proto.friends.extend(["Jane Doe", "John Smith"])
|
||||
person_proto.email = "john.doe@email.com"
|
||||
person_proto.phone = "123-456-7890"
|
||||
person_proto = person_proto.SerializeToString()
|
||||
|
||||
person_json = {
|
||||
"name": "John Doe",
|
||||
"age": 30,
|
||||
"friends": ["Jane Doe", "John Smith"],
|
||||
"email": "john.doe@email.com",
|
||||
"phone": "123-456-7890"
|
||||
}
|
||||
person_json = str(person_json).encode('utf-8')
|
||||
|
||||
FRAMEWORKS = [
|
||||
('Actix', 'tcc-actix', 'orange'),
|
||||
('ASP.NET', 'tcc-aspnet', 'blue'),
|
||||
('Flask', 'tcc-flask', 'grey'),
|
||||
('Express', 'tcc-express', 'red'),
|
||||
('Spring', 'tcc-spring', 'green'),
|
||||
# ('Express', 'tcc-express', 'red'),
|
||||
# ('Spring', 'tcc-spring', 'green'),
|
||||
]
|
||||
|
||||
ENDPOINTS = {
|
||||
|
@ -20,16 +34,16 @@ ENDPOINTS = {
|
|||
}
|
||||
|
||||
AVG_RUNS = 5
|
||||
helloworld_pb2
|
||||
|
||||
API_REQUESTS = [
|
||||
('/status/ok', 'GET', range(0, 30_000, 5000), None),
|
||||
# ('/status/ok', 'GET', range(0, 30_000, 5000), None),
|
||||
# ('/simulation/harmonic-progression?n=100000', 'GET', range(0, 30_000, 5000), None),
|
||||
# ('/simulation/json', 'GET', range(0, 30_000, 5000), None),
|
||||
# ('/image/save-big-image', 'POST', range(0, 500, 50), open('big-image.png', 'rb').read()),
|
||||
('/simulation/json', 'POST', range(0, 30_000, 5000), (person_json, "application/json")),
|
||||
# ('/image/save-big-image', 'POST', range(0, 500, 50), (open('big-image.png', 'rb').read(), "image/png")),
|
||||
# ('/image/load-small-image', 'GET', range(0, 30_000, 5000), None),
|
||||
# ('/static/small-image.png', 'GET', range(0, 30_000, 5000), None),
|
||||
# ('/image/load-big-image', 'GET', range(0, 500, 50), None),
|
||||
# ('/static/big-image.png', 'GET', range(0, 500, 50), None),
|
||||
# ('/static/nginx.html', 'GET', range(0, 30_000, 5000), None),
|
||||
('/simulation/protobuf', 'POST', range(0, 30_000, 5000), helloworld.SerializeToString()),
|
||||
('/simulation/protobuf', 'POST', range(0, 30_000, 5000), (person_proto.SerializeToString(), "application/protobuf")),
|
||||
]
|
||||
|
|
|
@ -1,5 +0,0 @@
|
|||
syntax = "proto3";
|
||||
|
||||
message MyObj {
|
||||
string message = 1;
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
syntax = "proto3";
|
||||
|
||||
message Person {
|
||||
string name = 1;
|
||||
int32 age = 2;
|
||||
repeated string friends = 3;
|
||||
string email = 4;
|
||||
string phone = 5;
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
# source: helloworld.proto
|
||||
# source: person.proto
|
||||
# Protobuf Python Version: 4.25.0
|
||||
"""Generated protocol buffer code."""
|
||||
from google.protobuf import descriptor as _descriptor
|
||||
|
@ -14,13 +14,13 @@ _sym_db = _symbol_database.Default()
|
|||
|
||||
|
||||
|
||||
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10helloworld.proto\"\x18\n\x05MyObj\x12\x0f\n\x07message\x18\x01 \x01(\tb\x06proto3')
|
||||
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0cperson.proto\"R\n\x06Person\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0b\n\x03\x61ge\x18\x02 \x01(\x05\x12\x0f\n\x07\x66riends\x18\x03 \x03(\t\x12\r\n\x05\x65mail\x18\x04 \x01(\t\x12\r\n\x05phone\x18\x05 \x01(\tb\x06proto3')
|
||||
|
||||
_globals = globals()
|
||||
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
|
||||
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'helloworld_pb2', _globals)
|
||||
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'person_pb2', _globals)
|
||||
if _descriptor._USE_C_DESCRIPTORS == False:
|
||||
DESCRIPTOR._options = None
|
||||
_globals['_MYOBJ']._serialized_start=20
|
||||
_globals['_MYOBJ']._serialized_end=44
|
||||
_globals['_PERSON']._serialized_start=16
|
||||
_globals['_PERSON']._serialized_end=98
|
||||
# @@protoc_insertion_point(module_scope)
|
|
@ -0,0 +1,31 @@
|
|||
import person_pb2
|
||||
import asyncio
|
||||
import aiohttp
|
||||
|
||||
async def fetch(session):
|
||||
obj = get_object()
|
||||
# async with session.post('http://172.25.96.1:9090/simulation/protobuf', data=obj.SerializeToString(),
|
||||
async with session.post('http://127.0.0.1:5000/simulation/protobuf', data=obj.SerializeToString(),
|
||||
headers={"content-type": "application/protobuf"}) as resp:
|
||||
print(resp.status)
|
||||
data = await resp.read()
|
||||
receiveObj = person_pb2.Person()
|
||||
receiveObj.ParseFromString(data)
|
||||
print(receiveObj)
|
||||
|
||||
async def go(loop):
|
||||
async with aiohttp.ClientSession(loop=loop) as session:
|
||||
await fetch(session)
|
||||
|
||||
def get_object():
|
||||
obj = person_pb2.Person()
|
||||
obj.name = "John Doe"
|
||||
obj.age = 30
|
||||
obj.friends.extend(["Jane Doe", "John Smith"])
|
||||
obj.email = "john.doe@email.com"
|
||||
obj.phone = "123-456-7890"
|
||||
return obj
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
loop.run_until_complete(go(loop))
|
||||
loop.close()
|
|
@ -0,0 +1,4 @@
|
|||
protobuf>=4.25.0
|
||||
matplotlib
|
||||
numpy
|
||||
docker
|
|
@ -14,7 +14,7 @@ FRAMEWORK_NAME = ""
|
|||
CONTAINER_NAME = ""
|
||||
URL_BASE = 'http://localhost:9090'
|
||||
|
||||
def send_request(url, method = 'GET', payload = None):
|
||||
def send_request(url, method = 'GET', data = None):
|
||||
success = False
|
||||
responses = {
|
||||
2: 0, # OK
|
||||
|
@ -27,7 +27,9 @@ def send_request(url, method = 'GET', payload = None):
|
|||
if method == 'GET':
|
||||
response = requests.get(url)
|
||||
elif method == 'POST':
|
||||
response = requests.post(url, data=payload, headers={'Content-Type': 'image/png'})
|
||||
payload = data[0]
|
||||
content_type = data[1]
|
||||
response = requests.post(url, data=payload, headers={'Content-Type': content_type})
|
||||
except:
|
||||
continue
|
||||
success = response.status_code == 200
|
||||
|
|
Loading…
Reference in New Issue