Пример #1
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello(ctx, name, times):
        """Docstrings for service methods appear as documentation in the wsdl.
        <b>What fun!</b>
        @param name the name to say hello to
        @param times the number of times to say hello
        @return the completed array
        """

        for i in range(times):
            yield u'Tere, %s' % name
Пример #2
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode, _returns=Iterable(Unicode), _body_style='bare')
    def say_hello(ctx, name):
        """
        Docstrings for service methods appear as documentation in the wsdl
        <b>what fun</b>
        @param name the name to say hello to
        @param the number of times to say hello
        @return the completed array
        """

        return u'Hello, %s' % name
Пример #3
0
class CourseWebService(ServiceBase):

	# 获得课程统计信息
	@srpc(_returns=Iterable(CourseStatisticsInfo))
	def getCourseStatistics():
		return CourseService.getCourseStatistics()

	# 获得学生统计信息
	@srpc(_returns=Iterable(StudentStatisticsInfo))
	def getStudentStatistics():
		return StudentService.getStudentStatistics()

	# 获取课程信息
	@srpc(_returns=Iterable(CourseInfo))
	def getAllCourseInfo():
		return CourseService.getAllCourseInfo()

	# 根据ID列表获取相应课程信息
	@srpc(Unicode, _returns=Iterable(CourseInfo))
	def getCourseByIds(idStr):
		return CourseService.getCourseInfoByIds(idStr.split(','))
Пример #4
0
class CampaignCrudService(ServiceBase):

    # create campaign if it's possible and return id
    @rpc(Campaign, _returns=UnsignedInteger32)
    def create_campaign(ctx, campaign):
        campaign_id = -1
        if campaign.id is None:
            scoped_session = start_engine()
            session = scoped_session()
            campaign_facade = CampaignFacade(session)
            campaign_facade.create_campaign(campaign=campaign)
            campaign_id = campaign_facade.get_campaign_by_name(
                name=campaign.name).id
            session.close()
        return campaign_id

    # delete campaign in cascade
    @rpc(Campaign)
    def delete_campaign(ctx, campaign):
        scoped_session = start_engine()
        session = scoped_session()
        facade = CampaignFacade(session)
        facade.delete_module(campaign=campaign)
        session.close()

    # update campaign
    @rpc(Campaign)
    def update_campaign(ctx, campaign):
        scoped_session = start_engine()
        session = scoped_session()
        facade = CampaignFacade(session)
        facade.update_module(module=campaign)
        session.close()

    # return campaign by id
    @rpc(Integer, _returns=Campaign)
    def get_campaign_by_id(ctx, campaign_id):
        scoped_session = start_engine()
        session = scoped_session()
        facade = CampaignFacade(session)
        campaign = facade.get_campaign_by_id(campaign_id=campaign_id)
        session.close()
        return campaign

    # return campaigns by module_id
    @rpc(Integer, _returns=Iterable(Campaign))
    def get_module_campaigns(ctx, module_id):
        scoped_session = start_engine()
        session = scoped_session()
        facade = CampaignFacade(session)
        campaigns = facade.get_campaigns_from_module_id(module_id=module_id)
        session.close()
        return campaigns
Пример #5
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello(self, name, times):
        """Docstrings for service methods appear as documentation in the wsdl.
        <b>What fun!</b>
        @param name: the name to say hello to
        @param times: the number of times to say hello
        @return  When returning an iterable, you can use any type of python iterable. Here, we chose to use generators.
        """

        for i in range(times):
            yield u'Hello, %s' % name
Пример #6
0
class Groups(ServiceBase):
    @rpc(_returns=Iterable(Unicode))
    def get_groups(ctx):
        groups_list = groups_get()
        for groups in groups_list:
            yield u'groups: %s' % groups.serialize_normal()

    @rpc(Unicode, _returns=Iterable(Unicode))
    def get_by_id_groups(ctx, id):
        groups = groups_get_id(id)
        yield u'groups: %s' % groups.serialize_normal()

    @rpc(Unicode, _returns=Iterable(Unicode))
    def create_groups(ctx, name):
        groups = groups_create({'name': name})
        yield u'groups: %s' % groups.serialize_normal()

    @rpc(Unicode, Unicode, _returns=Iterable(Unicode))
    def update_groups(ctx, id, name=None):
        groups = groups_update(id, {'name': name})
        yield u'groups: %s' % groups.serialize_normal()

    @rpc(Unicode, _returns=Iterable(Unicode))
    def delete_groups(ctx, id):
        groups = groups_delete(id)
        yield u'groups: %s' % groups.serialize_normal()

    @rpc(Unicode, Unicode, _returns=Iterable(Unicode))
    def add_member(ctx, id_group, id_user):
        groups = add_member(id_group, id_user)
        yield u'groups: %s' % groups.serialize_normal()
Пример #7
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode,Unicode,_returns=Iterable(Unicode))
    def say_hello(ctx, name, times):
        a = times.split(",")
        lat = a[0]
        lon = a[1]
        dynamodb = boto3.resource('dynamodb',
                        aws_access_key_id='AKIAJH7QCO7VUC43PFYQ',
                        aws_secret_access_key='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'
                        , region_name='us-east-2')
        dynamodb_client = boto3.client('dynamodb', aws_access_key_id = 'AKIAJH7QCO7VUC43PFYQ',
                        aws_secret_access_key = '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',
                        region_name = 'us-east-2')
        
        
        existing_tables = dynamodb_client.list_tables()['TableNames']

        if 'ItemTracker_tbl' not in existing_tables:

        # Create the DynamoDB table.

            table = dynamodb.create_table(TableName='ItemTracker_tbl',
                                          KeySchema=[{'AttributeName': 'itemtrackerId'
                                          , 'KeyType': 'HASH'}],
                                          AttributeDefinitions=[{'AttributeName': 'itemtrackerId'
                                          , 'AttributeType': 'S'}],
                                          ProvisionedThroughput={'ReadCapacityUnits': 5,
                                          'WriteCapacityUnits': 5})

            # Wait until the table exists.

            table.meta.client.get_waiter('table_exists').wait(TableName='ItemTracker_tbl')

        table = dynamodb.Table(name=u'ItemTracker_tbl')
        response  = table.query(KeyConditionExpression=Key('itemtrackerId').eq(name))

        if response['Count'] >0:
            table.update_item(Key={'itemtrackerId': name},
                              UpdateExpression='SET lat = list_append(lat, :i)'
                              , ExpressionAttributeValues={':i': [lat]},
                              ReturnValues='UPDATED_NEW')
            table.update_item(Key={'itemtrackerId': name},
                              UpdateExpression='SET lon = list_append(lon, :i)'
                              , ExpressionAttributeValues={':i': [lon]},
                              ReturnValues='UPDATED_NEW')
        else:
            print(name)
            table.put_item(Item={
                'itemtrackerId':name,
                'lat':[lat],
                'lon':[lon]
                })
Пример #8
0
class CrimeAPIService(ServiceBase):
	@srpc(float, float, float, float, _returns=Iterable(Unicode))
	def checkcrime(lat, lon, radius, key):
		output_dict = {}
		payload={'lat':lat,'lon':lon, 'radius':radius, 'key':'.'}
       		r=requests.get('https://api.spotcrime.com/crimes.json',params=payload) 
       		crime_data=r.json()
       		#yield crime_data

       		dict_crimetype = {}
       		dictCrimeTime = dictCrimeTimeInit()
		streetList =[]
       		for crime in (crime_data["crimes"]):
			
			# get crime type
	       		if (crime["type"]) not in dict_crimetype:
				dict_crimetype[crime["type"]] = 1
	       		else:
		       		dict_crimetype[crime["type"]] += 1
			
			# get crime time
			tme = time.strptime(crime["date"], "%m/%d/%y %I:%M %p")
			t = tme.tm_hour*60 + tme.tm_min
			if t == 0:
				t = 24*60
			t = t - 1
			i = t//(3*60)
			dictCrimeTime[dictCrimeTimeHelper[i]] += 1

			# get crime street
			#yield crime["address"]
			st = re.sub(r'\d+ BLOCK OF ',"", crime["address"] ) 
			st = re.sub(r'\d+ BLOCK ',"", st)
			st = re.sub(r'^\d+ ',"", st)
			for street in re.split(r' & | AND | and | And ', st):
				streetList.append(string.rstrip(string.lstrip(street)))

		#yield dict_crimetype
		output_dict["total_crime"] = len(crime_data["crimes"])
		output_dict["crime_type_count"] = dict_crimetype
		output_dict["event_time_count"] = dictCrimeTime
		
		# set up top 3 streets
		cnt = collections.Counter(streetList).most_common(3)
		top3 = []
		for entry in cnt:
			top3.append(entry[0])

		output_dict["the_most_dangerous_streets"] = top3
		#yield cnt

		yield output_dict
Пример #9
0
class HelloWorldService(ServiceBase):
    @rpc(String, UnsignedInteger, _returns=Iterable(String))
    def say_hello(ctx, name, times):
        """
        Docstrings for service methods do appear as documentation in the
        interface documents. <b>What fun!</b>
        :param name: The name to say hello to
        :param times: The number of times to say hello
        :returns: An array of 'Hello, <name>' strings, repeated <times> times.
        """

        for i in range(times):
            yield 'Hello, %s' % name
Пример #10
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello(ctx, name, times):
        """Docstrings for service methods appear as documentation in the wsdl.
        <b>What fun!</b>
        @param name the name to say hello to
        @param times the number of times to say hello
        @return the completed array
        """
        for i in range(times):
            yield u'Hello, %s' % name

    @rpc(Array(Name), _returns=Iterable(Unicode))
    def say_hello_plus(self, name_plus):
        print('---', name_plus)
        if not name_plus:
            yield 'None'

        for name in name_plus:
            print(name.first_name)
            print(name.last_name)
            yield name.first_name + name.last_name
Пример #11
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello(self, name, times):
        for i in range(times):
            yield 'Hello, %s' % name

    @rpc(Unicode, Integer, _returns=Unicode)
    def say_hello2(self, name, times):
        return ("yes")

    @rpc(Float, Float, _returns=Float)
    def livraison(self, poids, distance):
        return poids * (distance * (1 / 4))
Пример #12
0
class HelloWorldService(ServiceBase):
    @rpc(Integer, _returns=Iterable(Integer))
    def say_fibonacci(ctx, times):
        """Docstrings for service methods appear as documentation in the wsdl.
        <b>What fun!</b>
        @param name the name to say hello to
        @param times the number of times to say hello
        @return the completed array
        """
        a, b = 0, 1
        for i in range(times):
            if (a > times): break
            yield a
            a, b = b, a + b
Пример #13
0
class SomeService(Service):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello_as_file(ctx, name, times):
        if isinstance(ctx.transport, HttpTransportContext):
            file_name = "{}.xml".format(ctx.descriptor.name)

            ctx.transport.set_mime_type("application/xml")

            # Force download
            ctx.transport.add_header('Content-Disposition', 'attachment',
                                                             filename=file_name)

        for i in range(times):
            yield u'Hello, %s' % name
Пример #14
0
class HelloWorldService(Service):
    @rpc(Unicode(default='World'),
         UnsignedInteger(default=5),
         _returns=Iterable(Unicode))
    def say_hello(ctx, name, times):
        # workaround for Python2's lacking of nonlocal
        times = [times]

        def _cb(push):
            # This callback is called immediately after the function returns.

            if times[0] > 0:
                times[0] -= 1

                data = u'Hello, %s' % name
                print data

                # The object passed to the append() method is immediately
                # serialized to bytes and pushed to the response stream's
                # file-like object.
                push.append(data)

                # When a push-callback returns anything other than a deferred,
                # the response gets closed.
                return deferLater(reactor, 1, _cb, push)

        # This is Spyne's way of returning NOT_DONE_YET
        return Iterable.Push(_cb)

    @rpc(Unicode(default='World'), _returns=Iterable(Unicode))
    def say_hello_forever(ctx, name):
        def _cb(push):
            push.append(u'Hello, %s' % name)
            return deferLater(reactor, 0.1, _cb, push)

        return Iterable.Push(_cb)
class GlobalTextAnalyzer(ServiceBase):

    @rpc(Unicode, Unicode, _returns=Integer)
    def count_one_word(self, text, word):
        return sum(word == text_word for text_word in re.split(r'\W', text, flags=re.UNICODE))

    @rpc(Unicode, _returns=Iterable(CharCount))
    def count_characters(self, text):
        char_counts = {}
        for c in text:
            if c not in char_counts:
                char_counts[c] = 0
            char_counts[c] += 1
        for char, count in char_counts.iteritems():
            yield CharCount(char=char, count=count)

    @rpc(Unicode, _returns=Iterable(WordCount))
    def count_words(self, text):
        word_counts = {}
        for word in re.split(r'\W', text, flags=re.UNICODE):
            if word not in word_counts:
                word_counts[word] = 0
            word_counts[word] += 1
        for word, count in word_counts.iteritems():
            yield WordCount(word=word, count=count)

    @rpc(Unicode, _returns=Unicode)
    def make_caps(self, text):
        return text.upper()

    @rpc(Unicode, _returns=Iterable(WordCount))
    def count_words_on_web_page(self, url):

        html = get_page_content(url)
        for word, count in count_words_in_html(html):
            yield WordCount(word=word, count=count)
Пример #16
0
class SalesAgencyService(ServiceBase):
    def find_sales_agency(self):
        sales_agency = None
        with Pyro4.locateNS() as ns:
            uri = ns.lookup("sales_agency")
            sales_agency = Pyro4.Proxy(uri)
        if not sales_agency:
            raise ValueError("no sales agency found!")
        return sales_agency
# remote call and defines type/order of soap parameters

    @srpc(_returns=Iterable(Unicode))
    def get_properties():
        sales_agency = self.find_sales_agency()
        return sales_agency.properties
Пример #17
0
class ObjDetectorService(ServiceBase):
    @rpc(Unicode, _returns=Iterable(Unicode))
    def img_obj(self, image_file):
        img = cv2.imread(image_file)
        bboxs = detector(img)
        for label, value in bboxs.items():
            for v in value:
                x1 = str(round(v[0]))
                y1 = str(round(v[1]))
                x2 = str(round(v[2]))
                y2 = str(round(v[3]))
                score = str(round(v[4], 2))
                label = label
                ret = x1 + ',' + y1 + ',' + x2 + ',' + y2 + ',' + score + ',' + label
                yield ret
Пример #18
0
class HelloWorldService(ServiceBase):
    @rpc(Integer, _returns=str)
    def getOffer(ctx, id):
        try:
            offres_stage = get_offres_stage_from_json()
            for offre in offres_stage:
                if offre['id'] == id:
                    yield offre
        except:
            pass

    @rpc(_returns=Iterable(Integer))
    def getAvailableOffersIDs(ctx):
        for i in range(len(offres_stage)):
            yield i
Пример #19
0
class digitoService(ServiceBase):
    @rpc(Unicode, Unicode, _returns = Iterable(Unicode))
    def digito_verificador(ctx, rut, times):
        n_rut = rut.split('-')
        reversed_digits = map(int, reversed(str(n_rut[0])))
        factors = cycle(range(2, 8))
        s = sum(d * f for d, f in zip(reversed_digits, factors))
        mod = (-s) % 11
        if (mod == 10):
            mod = 'k'
        if (mod == 11):
            mod = 0
        if (str(mod) == n_rut[1]):
            yield ('Para el rut ' + str(rut) + ' ' + 'el digito verificador es '+ str(mod))
        else:
            yield('dv ingresado '+ str(n_rut[1]) + ' el dv correcto es '+ str(mod))
Пример #20
0
    class CrudService(ServiceBase):
        @rpc(M(UnsignedInteger32),
             _returns=T,
             _in_message_name='get_%s' % T_name,
             _in_variable_names={'obj_id': "%s_id" % T_name})
        def get(ctx, obj_id):
            return ctx.udc.session.query(T).filter_by(id=obj_id).one()

        @rpc(M(T),
             _returns=UnsignedInteger32,
             _in_message_name='put_%s' % T_name,
             _in_variable_names={'obj': T_name})
        def put(ctx, obj):
            if obj.id is None:
                ctx.udc.session.add(obj)
                ctx.udc.session.flush()  # so that we get the obj.id value

            else:
                if ctx.udc.session.query(T).get(obj.id) is None:
                    # this is to prevent the client from setting the primary key
                    # of a new object instead of the database's own primary-key
                    # generator.
                    # Instead of raising an exception, you can also choose to
                    # ignore the primary key set by the client by silently doing
                    # obj.id = None in order to have the database assign the
                    # primary key the traditional way.
                    raise ResourceNotFoundError('%s.id=%d' % (T_name, obj.id))

                else:
                    ctx.udc.session.merge(obj)

            return obj.id

        @rpc(M(UnsignedInteger32),
             _in_message_name='del_%s' % T_name,
             _in_variable_names={'obj_id': '%s_id' % T_name})
        def del_(ctx, obj_id):
            count = ctx.udc.session.query(T).filter_by(id=obj_id).count()
            if count == 0:
                raise ResourceNotFoundError(obj_id)

            ctx.udc.session.query(T).filter_by(id=obj_id).delete()

        @rpc(_returns=Iterable(T), _in_message_name='get_all_%s' % T_name)
        def get_all(ctx):
            return ctx.udc.session.query(T)
Пример #21
0
class HelloWorldService(ServiceBase):
    @rpc(_returns=Iterable(GraphPlotValue))
    def testDB(ctx):
        result = engine.execute('select * from dataSST')
        # for r in result:
        #     print(r)
        v = mapArray(result)

        return v

    @rpc(_returns=String)
    def listfoodService(ctx):

        my_schema = xmlschema.XMLSchema('./data/xsd/breakfast_menu.xsd')
        if (my_schema.is_valid('./data/xml/breakfast_menu.xml')):
            with open('./data/xml/breakfast_menu.xml') as f:
                resultXML = f.read()
            result = resultXML
        else:
            result = """<Error>Error NOT Valid</Error>"""

        return result

    @rpc(_returns=String)
    def getGrapXMLdata(ctx):

        results = engine.execute('select * from dataSST')
        dictTemp = []
        for r in results:
            tempData = {}
            tempData['date_use'] = r[3]
            tempData['x_lat'] = r[1]
            tempData['y_value'] = r[2]

            dictTemp.append(tempData)

        xml = dicttoxml.dicttoxml(dictTemp)

        my_schema = xmlschema.XMLSchema('./data/xsd/graphLat.xsd')
        root = etree.XML(xml)
        if (my_schema.is_valid(root)):
            result = xml
        else:
            result = """<Error>Error NOT Valid</Error>"""

        return result
Пример #22
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Array(Unicode))
    def say_hello(self, name, times):
        results = []
        for i in range(0, times):
            results.append('Hello {0}'.format(name))
        return results

    @rpc(Project, _returns=Unicode)
    def make_project(self, pro):
        return '{0}+{1}'.format(pro.name, pro.version)

    @rpc(Array(Project), _returns=Iterable(Unicode))
    def show_project(self, pros):
        if not pros:
            yield 'None'
        for pro in pros:
            yield pro.name + pro.version
Пример #23
0
class HelloWorldService(ServiceBase):
    @rpc(Integer,
         _out_variable_names=list(offres_stage[0].keys()),
         _returns=[type(v) for v in offres_stage[0].values()])
    def getOffer(ctx, id):
        try:
            offres_stage = get_offres_stage_from_json()
            for offre in offres_stage:
                if offre['id'] == id:
                    for k, v in offre.items():
                        yield v
        except:
            pass

    @rpc(_returns=Iterable(Integer))
    def getAvailableOffersIDs(ctx):
        for i in range(len(offres_stage)):
            yield i
Пример #24
0
class CurrenyConverterService(ServiceBase):
    @rpc(Unicode, Unicode, _returns=Iterable(Unicode))
    def getConversionRate(ctx, fromCurrency, toCurrency):
        url = 'http://api.fixer.io/latest?base=' + fromCurrency
        response = requests.get(url)
        #print('--    ')
        #print('date ' + response.json()['date'])
        #print('fromCurrency ' + fromCurrency)
        #print('toCurrency ' + toCurrency)
        yield response.json()['date']
        yield fromCurrency
        yield toCurrency
        if fromCurrency == toCurrency:
            #print('1')
            yield '1'
        else:
            #print(response.json()['rates'][toCurrency])
            yield str(response.json()['rates'][toCurrency])
        print('--    ')
Пример #25
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode, _returns=Iterable(Unicode))
    def say_hello(ctx, name):

        fh = open("./imagenes/captured.pgm", "wb")
        fh.write(base64.b64decode(name))
        fh.close()

        image = RecognizeFaces()

        if image is None:
            return None
        else:
            rut = str(imageId(image))

            if rut is None:
                return 'No hay registros asociados a la persona'
            else:
                return queryPerson(str(rut))
Пример #26
0
class wsSoap(ServiceBase):
    # Función principal del WS soap, calcula las ponderaciones de los de acuerdo a sus puntajes PSU y la carrera que eligen
    # @param ctx Contexto
    # @param filename Nombre del archivo por llegar
    # @param mimetype Tipo mime del archivo
    # @param content Contenido del archivo, en base64
    # @yields Entregan nombre final del archivo, tipo mime, contenido final del archivo
    @rpc(Unicode, Unicode, Unicode, _returns=Iterable(Unicode))
    def calculadorPuntajePsu(ctx, filename, mimetype, content):
        listofcarreras = initCarreras()
        listofdata = b64toS(content)
        listofruts = sToRutsPon(listofdata, listofcarreras)
        acomodar(listofcarreras, listofruts)
        getExcel(listofcarreras)
        excel = open("tmp.xlsx", 'rb').read()
        finalcontent = StoB64(excel)
        os.remove("tmp.xlsx")
        yield (finalname)
        yield (finalmime)
        yield (finalcontent)
Пример #27
0
class ManagerClass(ServiceBase):
    @rpc(Unicode, _returns=Iterable(Unicode))
    def request_manager(ctx, data):
        database = DataBaseConnection()
        data = json.loads(data)
        type = data['type']
        if type == 'add':
            # response = self.add_contact(data['name'], data['email'], data['phone'])
            response = database.add_contact(data['name'], data['email'],
                                            data['phone'])
            yield json.dumps({'response': response})
        elif type == 'update':
            response = database.update_contact(data['contact_id'],
                                               data['name'], data['email'],
                                               data['phone'])
            yield json.dumps({'response': response})
        elif type == 'search':
            response = database.search_contact(data['search_value'])
            yield json.dumps({'response': response})
        elif type == 'delete':
            response = database.delete_contact(data['contact_id'])
            yield json.dumps({'response': response})
Пример #28
0
class UserManagerService(Service):
    @rpc(M(UnsignedInteger32), _returns=User)
    def get_user(ctx, user_id):
        return ctx.udc.session.query(User).filter_by(id=user_id).one()

    @rpc(User, _returns=UnsignedInteger32)
    def put_user(ctx, user):
        if user.id is None:
            ctx.udc.session.add(user)
            ctx.udc.session.flush()  # so that we get the user.id value

        else:
            if ctx.udc.session.query(User).get(user.id) is None:
                # this is to prevent the client from setting the primary key
                # of a new object instead of the database's own primary-key
                # generator.
                # Instead of raising an exception, you can also choose to
                # ignore the primary key set by the client by silently doing
                # user.id = None
                raise ResourceNotFoundError('user.id=%d' % user.id)

            else:
                ctx.udc.session.merge(user)

        return user.id

    @rpc(M(UnsignedInteger32))
    def del_user(ctx, user_id):
        count = ctx.udc.session.query(User).filter_by(id=user_id).count()
        if count == 0:
            raise ResourceNotFoundError(user_id)

        ctx.udc.session.query(User).filter_by(id=user_id).delete()

    @rpc(_returns=Iterable(User))
    def get_all_user(ctx):
        return ctx.udc.session.query(User)
Пример #29
0
class StanSoapService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def ask_question(ctx, question, answer):
        """Ask Stan a question!
        <b>Ask Stan questions as a Service</b>

        @param name the name to say hello to
        @param times the number of times to say hello
        @return the completed array
        """

        yield u'To an artificial mind, all reality is virtual. How do they know that the real world isn\'t just another simulation? How do you?'

    @rpc()
    def server_exception(ctx):
        raise Exception("Server side exception example.")

    @rpc()
    def server_fault(ctx):
        raise Fault("Server", "Server side fault example.")

    @rpc()
    def client_fault(ctx):
        raise Fault("Client", "Client side fault example")
Пример #30
0
class CheckCrimeService(ServiceBase):
    @rpc(Float, Float, Float, _returns=Iterable(String))
    def checkcrime(ctx, lat, lon, radius):
        url = "https://api.spotcrime.com/crimes.json?lat=" + str(
            lat) + "&lon=" + str(lon) + "&radius=" + str(radius) + "&key=."
        response = urllib.urlopen(url)
        data = json.loads(response.read())
        data_crime = data["crimes"]
        #return data["crimes"]
        total_crime = len(data["crimes"])
        print "total crime:"
        print total_crime

        crimetypedict = {}
        crimetimedict = {
            '12:01am-3am': 0,
            '3:01am-6am': 0,
            '6:01am-9am': 0,
            '9:01am-12noon': 0,
            '12:01pm-3pm': 0,
            '3:01pm-6pm': 0,
            '6:01pm-9pm': 0,
            '9:01pm-12midnight': 0
        }
        pattern_search = r'([\d]*\sblock\s)*([\S\s]+\w)'
        street_names = {}

        for crime in data_crime:
            crime_date = datetime.datetime.strptime(crime['date'],
                                                    "%m/%d/%y %I:%M %p")
            if crime_date.replace(hour=0,
                                  minute=1) < crime_date <= crime_date.replace(
                                      hour=3, minute=0):
                crimetimedict['12:01am-3am'] += 1
            elif crime_date.replace(
                    hour=3, minute=1) < crime_date <= crime_date.replace(
                        hour=6, minute=0):
                crimetimedict['3:01am-6am'] += 1
            elif crime_date.replace(
                    hour=6, minute=1) < crime_date <= crime_date.replace(
                        hour=9, minute=0):
                crimetimedict['6:01am-9am'] += 1
            elif crime_date.replace(
                    hour=9, minute=1) < crime_date <= crime_date.replace(
                        hour=12, minute=0):
                crimetimedict['9:01am-12noon'] += 1
            elif crime_date.replace(
                    hour=12, minute=1) < crime_date <= crime_date.replace(
                        hour=15, minute=0):
                crimetimedict['12:01pm-3pm'] += 1
            elif crime_date.replace(
                    hour=15, minute=1) < crime_date <= crime_date.replace(
                        hour=18, minute=0):
                crimetimedict['3:01pm-6pm'] += 1
            elif crime_date.replace(
                    hour=18, minute=1) < crime_date <= crime_date.replace(
                        hour=21, minute=0):
                crimetimedict['6:01pm-9pm'] += 1
            else:
                crimetimedict['9:01pm-12midnight'] += 1

            if crime['type'] not in crimetypedict:
                crimetypedict[crime['type']] = 1
            else:
                crimetypedict[crime['type']] += 1

            text = crime['address'].replace('BLOCK BLOCK', 'BLOCK OF').replace('BLOCK OF', 'BLOCK').\
                    replace(' AND ', ' & ')
            address = re.search(pattern_search, text, re.I)
            if address:
                text, " >>> ", address.group(1), " >>> ", address.group(2)
                if address.group(2) not in street_names:
                    street_names[address.group(2)] = 1
                else:
                    street_names[address.group(2)] += 1

        street_names = sorted(street_names.items(),
                              key=operator.itemgetter(1),
                              reverse=True)
        dangerous_streets = [
            street_names[x][0] for x in range(min(3, len(street_names)))
        ]

        #yield {"total_crime": total_crimes, "crime_type_count": datadict, "event_time_count": crimetimedict}

        finalresult = {
            'total_crime': total_crime,
            'the_most_dangerous_streets': dangerous_streets,
            'crime_type_count': crimetypedict,
            "event_time_count": crimetimedict,
        }

        yield finalresult