1
0
mirror of https://github.com/actix/examples synced 2024-11-27 16:02:57 +01:00

Update protobuf to actix-web 2.0.0 (#249)

* Update to actix-web 2.0.0

* Add README.md
This commit is contained in:
Elliot Jackson 2020-02-06 18:17:23 +01:00 committed by GitHub
parent d59129c212
commit 443b8197ed
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 69 additions and 50 deletions

View File

@ -21,7 +21,7 @@ members = [
"multipart", "multipart",
"multipart-async-std", "multipart-async-std",
"openssl", "openssl",
# "protobuf", "protobuf",
"r2d2", "r2d2",
"redis", "redis",
"redis-session", "redis-session",

View File

@ -1,18 +1,17 @@
[package] [package]
name = "protobuf-example" name = "protobuf-example"
version = "0.1.0" version = "0.2.0"
authors = ["kingxsp <jin_hb_zh@126.com>"] authors = ["kingxsp <jin.hb.zh@outlook.com>, Yuki Okushi <huyuumi.dev@gmail.com>"]
workspace = ".." workspace = ".."
edition = "2018" edition = "2018"
[dependencies] [dependencies]
bytes = "0.4" bytes = "0.5.4"
futures = "0.1" env_logger = "0.7.1"
env_logger = "0.7.0" prost = "0.6.1"
derive_more = "0.15.0" prost-derive = "0.6.1"
prost = "0.5.0"
prost-derive = "0.5.0"
actix = "0.8.3" actix = "0.9.0"
actix-web = "1.0.8" actix-protobuf = "0.5.0"
actix-protobuf = "0.4.1" actix-rt = "1.0.0"
actix-web = "2.0.0"

28
protobuf/README.md Normal file
View File

@ -0,0 +1,28 @@
# protobuf
## Usage
### Server
```shell
# From workspace
cargo run --bin protobuf-example
# From ./protobuf
cargo run
```
### Client
```shell
# Dependencies
wget https://github.com/protocolbuffers/protobuf/releases/download/v3.11.2/protobuf-python-3.11.2.zip
unzip protobuf-python-3.11.2.zip
cd protobuf-3.11.2/python/
python3 setup.py install
pip3 install --upgrade pip
pip3 install aiohttp
# Client
python3 client.py
```

View File

@ -1,14 +1,16 @@
#!/usr/bin/env python3
# just start server and run client.py # just start server and run client.py
# wget https://github.com/google/protobuf/releases/download/v3.5.1/protobuf-python-3.5.1.zip # wget https://github.com/protocolbuffers/protobuf/releases/download/v3.11.2/protobuf-python-3.11.2.zip
# unzip protobuf-python-3.5.1.zip.1 # unzip protobuf-python-3.11.2.zip
# cd protobuf-3.5.1/python/ # cd protobuf-3.11.2/python/
# python3.6 setup.py install # python3 setup.py install
# pip3.6 install --upgrade pip # pip3 install --upgrade pip
# pip3.6 install aiohttp # pip3 install aiohttp
# python3 client.py
#!/usr/bin/env python
import test_pb2 import test_pb2
import traceback import traceback
import sys import sys
@ -46,7 +48,7 @@ async def fetch(session):
obj = test_pb2.MyObj() obj = test_pb2.MyObj()
obj.number = 9 obj.number = 9
obj.name = 'USB' obj.name = 'USB'
async with session.post('http://localhost:8081/', data=obj.SerializeToString(), async with session.post('http://127.0.0.1:8081/', data=obj.SerializeToString(),
headers={"content-type": "application/protobuf"}) as resp: headers={"content-type": "application/protobuf"}) as resp:
print(resp.status) print(resp.status)
data = await resp.read() data = await resp.read()
@ -63,4 +65,4 @@ async def go(loop):
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
loop.run_until_complete(go(loop)) loop.run_until_complete(go(loop))
loop.close() loop.close()

View File

@ -1,9 +1,3 @@
extern crate actix;
extern crate actix_protobuf;
extern crate actix_web;
extern crate bytes;
extern crate env_logger;
extern crate prost;
#[macro_use] #[macro_use]
extern crate prost_derive; extern crate prost_derive;
@ -18,26 +12,23 @@ pub struct MyObj {
pub name: String, pub name: String,
} }
fn index(msg: ProtoBuf<MyObj>) -> Result<HttpResponse> { async fn index(msg: ProtoBuf<MyObj>) -> Result<HttpResponse> {
println!("model: {:?}", msg); println!("model: {:?}", msg);
HttpResponse::Ok().protobuf(msg.0) // <- send response HttpResponse::Ok().protobuf(msg.0) // <- send response
} }
fn main() { #[actix_rt::main]
::std::env::set_var("RUST_LOG", "actix_web=info,actix_server=info"); async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=debug,actix_server=info");
env_logger::init(); env_logger::init();
let sys = actix::System::new("protobuf-example");
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.wrap(middleware::Logger::default()) .wrap(middleware::Logger::default())
.service(web::resource("/").route(web::post().to(index))) .service(web::resource("/").route(web::post().to(index)))
}) })
.bind("127.0.0.1:8081") .bind("127.0.0.1:8081")?
.unwrap()
.shutdown_timeout(1) .shutdown_timeout(1)
.start(); .run()
.await
println!("Started http server: 127.0.0.1:8081");
let _ = sys.run();
} }

View File

@ -1,13 +1,11 @@
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT! # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: test.proto # source: test.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message from google.protobuf import message as _message
from google.protobuf import reflection as _reflection from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports) # @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default() _sym_db = _symbol_database.Default()
@ -19,9 +17,9 @@ DESCRIPTOR = _descriptor.FileDescriptor(
name='test.proto', name='test.proto',
package='', package='',
syntax='proto3', syntax='proto3',
serialized_pb=_b('\n\ntest.proto\"%\n\x05MyObj\x12\x0e\n\x06number\x18\x01 \x01(\x05\x12\x0c\n\x04name\x18\x02 \x01(\tb\x06proto3') serialized_options=None,
serialized_pb=b'\n\ntest.proto\"%\n\x05MyObj\x12\x0e\n\x06number\x18\x01 \x01(\x05\x12\x0c\n\x04name\x18\x02 \x01(\tb\x06proto3'
) )
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
@ -39,21 +37,21 @@ _MYOBJ = _descriptor.Descriptor(
has_default_value=False, default_value=0, has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None, message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None, is_extension=False, extension_scope=None,
options=None), serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor( _descriptor.FieldDescriptor(
name='name', full_name='MyObj.name', index=1, name='name', full_name='MyObj.name', index=1,
number=2, type=9, cpp_type=9, label=1, number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'), has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None, message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None, is_extension=False, extension_scope=None,
options=None), serialized_options=None, file=DESCRIPTOR),
], ],
extensions=[ extensions=[
], ],
nested_types=[], nested_types=[],
enum_types=[ enum_types=[
], ],
options=None, serialized_options=None,
is_extendable=False, is_extendable=False,
syntax='proto3', syntax='proto3',
extension_ranges=[], extension_ranges=[],
@ -64,12 +62,13 @@ _MYOBJ = _descriptor.Descriptor(
) )
DESCRIPTOR.message_types_by_name['MyObj'] = _MYOBJ DESCRIPTOR.message_types_by_name['MyObj'] = _MYOBJ
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
MyObj = _reflection.GeneratedProtocolMessageType('MyObj', (_message.Message,), dict( MyObj = _reflection.GeneratedProtocolMessageType('MyObj', (_message.Message,), {
DESCRIPTOR = _MYOBJ, 'DESCRIPTOR' : _MYOBJ,
__module__ = 'test_pb2' '__module__' : 'test_pb2'
# @@protoc_insertion_point(class_scope:MyObj) # @@protoc_insertion_point(class_scope:MyObj)
)) })
_sym_db.RegisterMessage(MyObj) _sym_db.RegisterMessage(MyObj)