From c377c32168de2c9fdc73e9c29d8ed2425e1d8395 Mon Sep 17 00:00:00 2001 From: Bryan Duxbury Date: Thu, 2 Sep 2010 15:37:19 +0000 Subject: [PATCH] THRIFT-257. py: Support validation of required fields Patch: Esteve Fernandez git-svn-id: https://svn.apache.org/repos/asf/incubator/thrift/trunk@991987 13f79535-47bb-0310-9956-ffa450edef68 --- compiler/cpp/src/generate/t_py_generator.cc | 29 ++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/compiler/cpp/src/generate/t_py_generator.cc b/compiler/cpp/src/generate/t_py_generator.cc index 92471aca..38eb20ef 100644 --- a/compiler/cpp/src/generate/t_py_generator.cc +++ b/compiler/cpp/src/generate/t_py_generator.cc @@ -90,6 +90,7 @@ class t_py_generator : public t_generator { void generate_py_struct_definition(std::ofstream& out, t_struct* tstruct, bool is_xception=false, bool is_result=false); void generate_py_struct_reader(std::ofstream& out, t_struct* tstruct); void generate_py_struct_writer(std::ofstream& out, t_struct* tstruct); + void generate_py_struct_required_validator(std::ofstream& out, t_struct* tstruct); void generate_py_function_helpers(t_function* tfunction); /** @@ -323,7 +324,7 @@ string t_py_generator::render_includes() { string t_py_generator::render_fastbinary_includes() { return "from thrift.transport import TTransport\n" - "from thrift.protocol import TBinaryProtocol\n" + "from thrift.protocol import TBinaryProtocol, TProtocol\n" "try:\n" " from thrift.protocol import fastbinary\n" "except:\n" @@ -853,11 +854,37 @@ void t_py_generator::generate_py_struct_writer(ofstream& out, indent() << "oprot.writeFieldStop()" << endl << indent() << "oprot.writeStructEnd()" << endl; + generate_py_struct_required_validator(out, tstruct); + indent_down(); out << endl; } +void t_py_generator::generate_py_struct_required_validator(ofstream& out, + t_struct* tstruct) { + indent(out) << "def validate(self):" << endl; + indent_up(); + + const vector& fields = tstruct->get_members(); + + if (fields.size() > 0) { + vector::const_iterator f_iter; + + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + t_field* field = (*f_iter); + if (field->get_req() == t_field::T_REQUIRED) { + indent(out) << "if self." << field->get_name() << " is None:" << endl; + indent(out) << " raise TProtocol.TProtocolException(message='Required field " << + field->get_name() << " is unset!')" << endl; + } + } + } + + indent(out) << "return" << endl << endl; + indent_down(); +} + /** * Generates a thrift service. * -- 2.17.1