示例#1
0
def service_factory(service):
    u"""
    Оборачивает класс сервиса в приложение django c basic auth
    """

    application_tns = service.application_tns if hasattr(
        service, 'application_tns') else 'smartbps'
    service_name = service.service_name if hasattr(
        service, 'service_name') else service.__name__.lower()

    # 20 Мб
    max_content_length = (1024 * 1024 * 20)
    app = DjangoApplication(Application([service],
                                        tns=application_tns,
                                        name='smartbps',
                                        in_protocol=Soap11(validator='lxml'),
                                        out_protocol=Soap11()),
                            max_content_length=max_content_length)

    @csrf_exempt
    def service_wrapper(request):
        u"""
        При не авторизованном запросе (смотрим по сессии),
        выдаем запрос на авторизацию http401
        При получении ответа, запоминаем в сессию логин и пароль.
        Если в сессии есть логин-пароль, то проверяем его при каждом запросе
        (а вдруг поддерживается длинная сессия и пароль нужно поменять)
        """

        key = 'web_service:auth_%s' % service_name

        # Авторизован
        if key in request.session:
            uname, passwd = request.session[key]
            if uname == service.login and passwd == service.password:
                return app(request)

        # Обработка запроса авторизации
        if 'HTTP_AUTHORIZATION' in request.META:
            auth = request.META['HTTP_AUTHORIZATION'].split()
            if len(auth) == 2:
                method, user_pass = auth
                if method == "Basic":
                    uname, passwd = base64.b64decode(user_pass).split(':')
                    if uname == service.login and passwd == service.password:
                        request.session[key] = [uname, passwd]
                        return app(request)

        # Нужно отправить запрос на авторизацию
        response = HttpResponse()
        response.status_code = 401
        response['WWW-Authenticate'] = 'Basic realm="soap_%s"' % service_name
        return response

    return service_wrapper
示例#2
0
                # TODO:需要做在线人数统计


                user = json.dumps(imanageuser, default=UserInfo.obj_2_json)
                user = SecretHelper.AESEncrypt(user)
                Msg = str(user, encoding = "utf8")
            else:
                Msg = "['认证失败']"
        else:

            returnStatusCode = ''

            returnStatusCode, userInfo = LogOnService.UserLogOn(Account, Password, '', False, ctx.transport.req["REMOTE_ADDR"])

            if returnStatusCode == StatusCode.statusCodeDic.get('OK'):
                user = json.dumps(userInfo, default=UserInfo.obj_2_json)
                user = SecretHelper.AESEncrypt(user)
                Msg = str(user, encoding="utf8")
            else:
                Msg = "['认证失败']"

        yield Msg


login_application = Application([LoginService],
                          tns='Usable-Programming.LoginService.CheckLogin',
                          in_protocol = JsonDocument(validator='soft'),
                          out_protocol=JsonDocument())

login_service = csrf_exempt(DjangoApplication(login_application))
示例#3
0
def infraction_management():
    django_soap_app = DjangoApplication(soap_app)
    infraction_soap_app = csrf_exempt(django_soap_app)

    return infraction_soap_app
示例#4
0
            else:
                return "false"
        except User.DoesNotExist as e:
            raise Fault(faultstring=str(e))

    @rpc(String, _returns=Array(String))
    def data_user(ctx, email):
        try:
            user = User.objects.get(email=email)
            return [
                "true",
                str(user.id),
                str(user.id_document),
                str(user.name),
                str(user.lastname),
                str(user.email),
                str(user.password),
                str(user.telephone)
            ]
        except User.DoesNotExist as e:
            raise Fault(faultstring=str(e))


application = Application([RegisterUser],
                          tns='spyne.examples.hello',
                          in_protocol=Soap11(validator='lxml'),
                          out_protocol=Soap11())
# This module resides in a package in your Django
# project.
payco_app = csrf_exempt(DjangoApplication(application))
示例#5
0
                        value = city_state.blue_cubes - 1
                    http_request.POST = QueryDict.fromkeys(key, value=value)
                    request = Request(http_request)
                    request.user = user
                    response = update_city_state(request, city_state.id,
                                                 session.session_hash)
                    res = "Aceite" if response.status_code == 200 else "Não aceite"
                else:
                    http_request.POST = QueryDict.fromkeys(
                        ['research_station'], value=True)
                    request = Request(http_request)
                    request.user = user
                    response = update_city_state(request, city_state.id,
                                                 session.session_hash)
                    res = "Aceite" if response.status_code == 200 else "Não aceite"
                return res
            else:
                raise InvalidCredentialsError('User')
        except ObjectDoesNotExist:
            raise ResourceNotFoundError('Session')


soap_app = Application(
    [InfoJogoService, FazJogadaService],
    'pandemic.soap',
    in_protocol=Soap11(validator='lxml'),
    out_protocol=Soap11(),
)

pandemic_soap_service = csrf_exempt(DjangoApplication(soap_app))
示例#6
0
class NoteService(Service):
    @rpc(Integer, _returns=ComplexNote)
    def get_note(ctx, pk):
        try:
            return Note.objects.get(pk=pk)
        except Note.DoesNotExist:
            raise ResourceNotFoundError('ComplexNote')

    @rpc(Integer, _returns=Iterable(ComplexNote))
    def get_notes(ctx, pk):
        try:
            return Note.objects.all()
        except Note.DoesNotExist:
            raise ResourceNotFoundError('ComplexNote')

    @rpc(ComplexNote, _returns=ComplexNote)
    def create_note(ctx, note):
        try:
            return Note.objects.create(**note.as_dict())
        except IntegrityError:
            raise ResourceAlreadyExistsError('ComplexNote')


app = Application([NoteService],
                  'epg.aban',
                  in_protocol=Soap11(validator='lxml'),
                  out_protocol=Soap11(),
                  )

note_soap_service = csrf_exempt(DjangoApplication(app))
示例#7
0

'''class PostService(ServiceBase):
	@rpc(Unicode, _returns=Unicode)
	def create(ctx, str):
		post = Post(name=str)
		post.save
		print ("EXITO")
		return 'Success'

	@rpc(_returns=Iterable(Unicode))
	def get(ctx):
		return Post.objects.filter(created_date__lte=timezone.now()).order_by('created_date')'''


class GetService(ServiceBase):
    @rpc(Unicode, _returns=Unicode)
    def get(ctx, name):
        return Post.objects.filter(name)
        #return Post.objects.filter(name)


app = Application(
    [HelloWorldService, GetService],
    'spyne.examples.django',
    in_protocol=Soap11(validator='lxml'),
    out_protocol=Soap11(),
)

hello_world_service = csrf_exempt(DjangoApplication(app))
示例#8
0
        except FieldContainer.DoesNotExist:
            raise ResourceNotFoundError('Container_submitseq')

    @rpc(Container_submitseq, _returns=Container_submitseq)
    def create_container(ctx, container):
        try:
            return FieldContainer.objects.create(**container.as_dict())
        except IntegrityError:
            raise ResourceAlreadyExistsError('Container_submitseq')

class ExceptionHandlingService_submitseq(DjangoServiceBase):
    """Service for testing exception handling."""

    @rpc(_returns=Container_submitseq)
    def raise_does_not_exist(ctx):
        return FieldContainer.objects.get(pk=-1)

    @rpc(_returns=Container_submitseq)
    def raise_validation_error(ctx):
        raise ValidationError('Is not valid.')


app_submitseq = Application([Service_submitseq, ContainerService_submitseq,
    ExceptionHandlingService_submitseq], 'pathopred.bioinfo.se',
    in_protocol=Soap11(validator='soft'), out_protocol=Soap11())
#wsgi_app_submitseq = WsgiApplication(app_submitseq)

submitseq_service = csrf_exempt(DjangoApplication(app_submitseq))

#}}}
示例#9
0

def save_order_to_database(user_id, food_id, amount):
    if amount >= 10:
        return False

    return True


class OrderFoodService(ServiceBase):
    @rpc(Mandatory.Integer,
         Mandatory.Integer,
         Mandatory.Integer,
         _returns=Mandatory.String)
    def order_food(ctx, user_id, food_id, amount):
        result = save_order_to_database(user_id, food_id, amount)
        if result:
            return 'ok'
        else:
            return "We don't have enough supplies to fulfill your order. Sorry"


order_food_service = csrf_exempt(
    DjangoApplication(
        Application(
            [OrderFoodService],
            'webdbhazi.services.order',
            in_protocol=Soap11(),
            out_protocol=Soap11(),
            interface=Wsdl11(),
        )))
示例#10
0
    if request.META.has_key('HTTP_X_FORWARDED_FOR'):
        ip = request.META['HTTP_X_FORWARDED_FOR']
    else:
        ip = request.META['REMOTE_ADDR']
    SSP = SSOSessionOperation()
    username = SSP.check_login_by_ip(ip)
    if username == '':
        result['code'] = 400
        result['message'] = '已注销'
        return JsonResponse(result)
    else:
        result['code'] = 200
        result['username'] = username
        result['message'] = '用户信息'
        return JsonResponse(result)


def check_session_expire(request):
    """
    校验登录的session是否过期
    :param request:
    :return:
    """
    result = {}
    SSP = SSOSessionOperation()
    SSP.check_session_expire_time()
    return JsonResponse(result)


sso_wsdl = csrf_exempt(DjangoApplication(application))
示例#11
0
#

from django.views.decorators.csrf import csrf_exempt

from spyne.server.django import DjangoApplication
from spyne.model.primitive import String, Integer
from spyne.model.complex import Iterable
from spyne.service import ServiceBase
from spyne.interface.wsdl import Wsdl11
from spyne.protocol.soap import Soap11
from spyne.application import Application
from spyne.decorator import rpc


class HelloWorldService(ServiceBase):
    @rpc(String, Integer, _returns=Iterable(String))
    def say_hello(ctx, name, times):
        for i in xrange(times):
            yield 'Hello, %s' % name


hello_world_service = csrf_exempt(
    DjangoApplication(
        Application(
            [HelloWorldService],
            'spyne.examples.django',
            in_protocol=Soap11(),
            out_protocol=Soap11(),
            interface=Wsdl11(),
        )))
示例#12
0
    location = Unicode
    time = Unicode
    level = Unicode
    message = Unicode
    #多少都可以,前提是客户端得给你传过来,你才能接收到,但是客户端有的字段,你这里必须有,否则会报错,


#第四步:声明服务的类,类的方法,就是客户端访问的服务,业务逻辑,操作都在这里面,
#project就是字典,或者对象,

class SServices(ServiceBase):
    @rpc(Project, _returns=Unicode)
    def make_func(self, project):
        # return "链接成功,webservice 服务器已接收到数据"
        print(project)
        #业务逻辑放这里,把接收到的参数就是project,可以保存到数据库,等操作,
        return "save success"

    # 返回数组
    @rpc(Iterable(String), _returns=Iterable(String))
    def json_ret(self, params1):
        a = ["test", "111", "ceshi", "222"]
        return a


soap_app = Application([SServices],
                           'WebServices',
                           in_protocol=Soap11(validator="lxml"),
                           out_protocol=Soap11())
server_app = csrf_exempt(DjangoApplication(soap_app))
示例#13
0
                'requestId': {
                    'value': requestId,
                },
                'checkpoint': {
                    'value': False,
                },
                'destination': {
                    'value': False
                }
            }
        }
        headers = {'Content-type': 'application/json'}
        json_payload = json.dumps(payload)
        r = requests.post('http://localhost:8080/engine-rest/message',
                          headers=headers,
                          data=json_payload)

        if (r.status_code == 200 or r.status_code == 204):
            return 'Insurance Created'
        else:
            return 'Failed to Create Insurance'


logistic_service = Application([LogisticService],
                               tns='com.if4150.logistic',
                               in_protocol=Soap11(validator='lxml'),
                               out_protocol=Soap11())

django_logistic_service = DjangoApplication(logistic_service)
logistic_service = csrf_exempt(django_logistic_service)
示例#14
0
        #Process params from request
        params = get_xml_as_object(xml, AnyDict)
        params = clear_list(params)
        #Handle request
        id, description = handle_request(params)
        res = '''<?xml version="1.0" encoding="UTF-8"?>
                 <result>
                   <id>%s</id>
                   <description>%s</description>
                 </result>''' % (id, description, )
        return res.decode('utf8')

    @srpc(AnyXml, _returns=AnyDict)
    def test(xml):
        params = get_xml_as_object(xml, AnyDict)
        params = clear_list(params)
        method = get_method(params)
        c = wic_client()
        if not hasattr(c, method):
            raise Exception, 'Not implemented method: %s' % method
        kwargs = params[method]
        kwargs = getattr(c, method)(**kwargs)
        params[method] = kwargs
        return params

soap_services = csrf_exempt(DjangoApplication(Application([WebService],
        'soap.services',
        in_protocol=Soap11(),
        out_protocol=Soap11(),
    )))
示例#15
0
        return None

    @rpc(Unicode, Unicode, _returns=Unicode)
    def interactiveUrl(ctx, ticket, sessionID):
        print('interactiveUrl')
        print(ticket)
        print(sessionID)
        return 'http://localhost/test'

    @rpc(Unicode, _returns=Unicode)
    def interactiveDone(ctx, ticket):
        print('interactiveDone()')
        print(ticket)
        return 'Done'

    @rpc(Unicode, Unicode, _returns=Unicode)
    def interactiveRejected(ctx, ticket, reason):
        print('interactiveRejected()')
        print(ticket)
        print(reason)
        return 'Interactive mode rejected'


app = Application([QuickBooksService],
                  'http://developer.intuit.com/',
                  in_protocol=Soap11(validator='lxml'),
                  out_protocol=Soap11())

qb_service = csrf_exempt(DjangoApplication(app))
示例#16
0
def consulta():
    django_soap_app = DjangoApplication(soap_app)
    my_soap_app = csrf_exempt(django_soap_app)

    return my_soap_app
# if __name__ == '__main__':

#     import logging

#     from wsgiref.simple_server import make_server

#     logging.basicConfig(level=logging.DEBUG)
#     logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)

#     logging.info("listening to http://127.0.0.1:8010")
#     logging.info("wsdl is at: http://localhost:8010/?wsdl")

#     server = make_server('127.0.0.1', 8010, wsgi)
#     server.serve_forever()

argus_api = DjangoApplication(application)


def get_wsdl_file(request):
    with open('fito/UZ21.swdl', 'r') as f:
        docs = f.read()
    return HttpResponse(docs, content_type='text/xml; charset=utf-8')


@csrf_exempt
def service_dispatch(request):
    if request.get_full_path() in ('/srv/ws/uz2?wsdl', '/srv/ws/uz2_uz2?wsdl'):
        return get_wsdl_file(request)
    return argus_api(request)
示例#18
0
                continue

            if access_profile.role is not None:
                db_access_role = open_role_by_code(access_profile.role.code)

            if db_access_role is None:
                raise error.ResourceNotFoundError('accessRole')

            profile, _ = AccessProfile.objects.update_or_create(
                user=db_user,
                unit_type=ContentType.objects.get_for_model(db_organization),
                unit_id=db_organization.id,
                role=db_access_role,
                headquater=db_headquarter)


soap_app = Application(
    [WFMPortalService],
    'http://outsourcing.verme.ru/api/soap',
    in_protocol=Soap11(validator='lxml'),
    out_protocol=Soap11(),
)

rest_app = Application([WFMPortalService],
                       'http://outsourcing.verme.ru/api/soap',
                       in_protocol=JsonDocument(validator='soft'),
                       out_protocol=JsonDocument())

outsourcing_soap_service = csrf_exempt(DjangoApplication(soap_app))
outsourcing_rest_service = csrf_exempt(DjangoApplication(rest_app))
示例#19
0
        except:
            yield "['认证失败']"

        if PublicController.ApiIsAuthorized(
                user, "UserManagement.GetUserListByPage"):

            dtUser = UserSerivce.GetDTByPage(
                user, SearchFilter.TransfromFilterToSql(filter, False), '', '',
                rows, sort + ' ' + order)
            recordCount = dtUser.count
            pageValue = dtUser.page(page)

            userTmp = ''
            for role in pageValue:
                userTmp = userTmp + ', ' + json.dumps(role, cls=DateEncoder)
                userTmp = userTmp.strip(',')
            returnValue = '{"total": ' + str(
                recordCount) + ', "rows":[' + userTmp + ']}'
            yield returnValue
        else:
            yield "['权限不足']"


useradmin_application = Application(
    [UserAdminService],
    tns='Usable-Programming.UserAdminService.GetUserPageDTByDepartmentId',
    in_protocol=JsonDocument(validator='soft'),
    out_protocol=JsonDocument())

useradmin_service = csrf_exempt(DjangoApplication(useradmin_application))
示例#20
0
        '''
        保存推送过来的地址信息接口
        :param request: 接收的请求
        :return: 地址保存结果
        '''
        logging.info('接收到请求:%s' % request)
        rq_decode = request_base64_decode(request)
        logging.info('请求参数:%s' % rq_decode)
        env_tree = XmlEnvelopeTree(rq_decode)
        dict_data = env_tree.xml_to_dict()
        logging.info('请求体字典数据:%s' % dict_data)
        result = saveaddr_to_db(dict_data)
        xml_tree = XmlEnvelopeTree(result)
        logging.info('响应数据:%s' % xml_tree.envelope_encode())
        return base64.b64encode(
            xml_tree.envelope_encode().encode('utf-8')).decode()


soap_app = Application(
    [OrderServices],
    tns='webservice_test.myservice.views',
    # in_protocol=HttpRpc(validator='soft'),
    # 'SampleServices',
    in_protocol=Soap11(validator="lxml"),
    out_protocol=Soap11())
django_app = DjangoApplication(soap_app)
sum_app = csrf_exempt(django_app)
es = get_session()
init_db(es[0])
logging.info("listening to http://127.0.0.1:8000")
logging.info("wsdl is at: http://localhost:8000/OrderServices?wsdl")
示例#21
0
                else:
                    i["PartName"]=""
            if len(data_SN) == qty:
                return str(data_SN)
            else:
                return "Box had't binding finished"
        else:
            return "Query NO data"
#
application = Application([HelloWorldService],
    tns='spyne.examples.hello',
    in_protocol=Soap11(validator='lxml'),
    out_protocol=Soap11()
)
# # This module resides in a package in your Django
information_app = csrf_exempt(DjangoApplication(application))

def Information_Box(request):
    try:
        box_item = request.GET.get("box",'')
        check_box = list(Box.objects.filter(BoxId=box_item).values("Id"))
        if len(check_box) !=0:
            data =[]
            data_SN = list(SerialNumberInfo.objects.filter(BoxIdBindingId=int(check_box[0]["Id"])).values_list("SerialNumber"))
            for i in data_SN:
                data.append(i[0])
            return HttpResponse(json.dumps(data,ensure_ascii=False),content_type="application/json,charset=utf-8")
        else:
            return restful.params_error(message="NO data",data=box_item)
    except Exception as e:
        return restful.params_error(message=e)