Example #1
0
    def post(self):

        if 'name' not in self.request.arguments.keys():
            self.write('no')
            return
        else:
            name = ''.join(self.request.arguments['name'])

        if 'oldid' not in self.request.arguments.keys():
            self.write('no')
            return
        else:
            oldid = int(''.join(self.request.arguments['oldid']))

        try:
            mark = Business.add_mark(name)

            if mark is not None:
                if Business.q_mark(oldid, 0, mark) is not None:
                    self.write('ok')
            else:
                self.write('no')
                return

        except DBException as e:
            self.write('no')
            return
Example #2
0
	def post(self):

                if 'name' not in self.request.arguments.keys():
                        self.write('no')
			return
                else:
                        name = ''.join(self.request.arguments['name'])

		if 'oldid' not in self.request.arguments.keys():
                        self.write('no')
			return
                else:
			oldid= int(''.join(self.request.arguments['oldid']))

		try:
			mark = Business.add_mark(name)

			if mark is not None:
				if Business.q_mark(oldid,0,mark) is not None:
					self.write('ok')
			else:
				self.write('no')
                        	return

		except DBException as e:
			self.write('no')
			return
Example #3
0
    def _qid_search(self, data):

        username = self.get_secure_cookie('uname')
        index_dict = {
            'username': username,
            'title': '新旧题对比展示',
            'front_is_able': 'disabled',
            'next_is_able': 'disabled',
            "front": "",
            "next": ""
        }

        old_dict = self._old_question(data)
        new_dict = self._new_question(data)

        if old_dict is None or new_dict is None:
            self.write('搜无此题')
            return

        combine_dict = dict(index_dict, **old_dict)
        combine_dict = dict(combine_dict, **new_dict)

        mark_list = Business.q_mark_list()
        mark_dict = {'mark_list': mark_list}
        combine_dict = dict(combine_dict, **mark_dict)

        systematics_list = Business.get_systematics(data)
        systematics_dict = {'systematics_list': systematics_list}

        combine_dict = dict(combine_dict, **systematics_dict)

        self.render("new_old_question_show.html", **combine_dict)
Example #4
0
	def _qid_search(self,data):

		username = self.get_secure_cookie('uname')
		index_dict = {'username':username,'title' : '新旧题对比展示','front_is_able' : 'disabled','next_is_able' : 'disabled',"front":"","next":""}

		old_dict = self._old_question(data)
		new_dict = self._new_question(data)
		
		if old_dict is None or new_dict is None:
			self.write('搜无此题')
			return

		combine_dict = dict(index_dict,**old_dict)
		combine_dict = dict(combine_dict,**new_dict)

		mark_list = Business.q_mark_list()
		mark_dict = {'mark_list' : mark_list}
		combine_dict = dict(combine_dict,**mark_dict)

		systematics_list = Business.get_systematics(data)
		systematics_dict = {'systematics_list' : systematics_list}

		combine_dict = dict(combine_dict,**systematics_dict)

		self.render("new_old_question_show.html",**combine_dict)
Example #5
0
    def test_b_withdraw(self):

        account2 = Business("kenny", "19920010877490827", "788978742", 25000,
                            4321)

        testNewbalance = account2.b_withdraw(2000, 4321)
        self.assertEqual(testNewbalance, 23000)
Example #6
0
    def __init__(self, ip, port, db_ip="localhost", db_port=CALL_DB_PORT):
        self.ip = ip
        self.port = port
        self.db_ip = db_ip
        self.db_port = db_port
        self._type = -1
        self._status = -1
        self._error = ""

        Business.__init__(self, "forward", ip, port)
Example #7
0
	def get(self):

		title = '首页'
	
		username = self.get_secure_cookie('uname')

		subject_list = ()
		type_list = ()
		subject_list = Business.q_subject_list()
		type_list = Business.q_type_list()

		self.render('index.html',title = title,username = username,type_list = type_list,subject_list = subject_list)
Example #8
0
 def __init__(self, ip, port):
     Hancock.control_clients.add(self)
     Business.__init__(self, 'control', ip, port)
     # 初始化一些基础信息,供下面调用
     self.request = None
     self.device_type = None
     self.device_id = None
     self.device = None
     self.version = None
     self.verify = None
     self.author = None
     self.body = None
     self.length = None
Example #9
0
    def test_b_transfer(self):

        account2 = Business("kenny", "19920010877490827", "788978742", 25000,
                            4321)

        amount = 30000
        self.assertGreater(amount, account2.balance)

        testamount = account2.b_transfer(30000, 4321)
        self.assertEqual(testamount, 0)

        testpassword = account2.b_transfer(4000, 9087)
        self.assertEqual(testpassword, "")
Example #10
0
    def post(self):

        if 'username' not in self.request.arguments.keys():
            self.write('no')
            return
        else:
            username = ''.join(self.request.arguments['username'])

        if 'password' not in self.request.arguments.keys():
            self.write('no')
            return
        else:
            password = ''.join(self.request.arguments['password'])

        try:
            if Business.check_user(username, password):
                self.set_secure_cookie('uname', username, expires_days=None)
                self.write('ok')

            else:
                self.write('no')
        except DBException:

            self.write('no')
            return
Example #11
0
def search(lat, lng, distance):
    """
    Searches the Foursquare API (Max Limit = 50)

    :param lat: Latitude of the request
    :param long: Longitude of the request
    :param distance: Distance to search (meters)
    :returns: List of retrieved venues
    """

    url = SEARCH_URL.format(lat, lng, distance, CATEGORY_ID, CLIENT_ID,
                            CLIENT_SECRET, time.strftime("%Y%m%d"))
    venue_list = []

    try:
        data = make_request(url)

        for item in data['response']['groups'][0]['items']:
            venue = item['venue']
            venue_list.append(
                Business(venue['name'], venue['location']['address'],
                         venue['rating'], venue['ratingSignals'],
                         venue['stats']['checkinsCount']))
    except Exception, e:
        print e
Example #12
0
def split_data(businessfile, reviewfile, number_sets, train_weight):
    all_sets = {}
    for i  in range(1, number_sets+1):
        all_sets["train" + str(i)] = {}
        all_sets["test" + str(i)] = {}

    with open(businessfile) as rst:
        for line in rst:
            jline = json.loads(line)
            b_id = jline['business_id']
            set_num = rd.randint(1, number_sets)
            isTrain = rd.randint(1, 10)
            if isTrain > train_weight:
                dict_type = "test"
            else:
                dict_type = "train"
            dict_temp = {}
            if (dict_type + str(set_num)) in all_sets.keys():
                dict_temp = all_sets[dict_type + str(set_num)]
            dict_temp[b_id] = Business(jline)
            all_sets[dict_type + str(set_num)]  = dict_temp

    all_keys = all_sets.keys()
    with open(reviewfile) as rvw:
        for line in rvw:
            jline = json.loads(line)
            b_id = jline['business_id']
            for i_dict in all_keys:
                if b_id in all_sets[i_dict].keys():
                    dict_temp = all_sets[i_dict]
                    dict_temp[b_id].add_review(jline)
                    all_sets[i_dict]  = dict_temp
    return all_sets
Example #13
0
def search(lat, lng, distance, query):
    """
    Searches the Foursquare API (Max Limit = 50)

    :param lat: Latitude of the request
    :param long: Longitude of the request
    :param distance: Distance to search (meters)
    :param query: The niche, i.e. restaurants, bars, etc
    :returns: List of retrieved venues
    """

    url = SEARCH_URL.format(lat, lng, distance, query, F_CLIENT_ID,
                            F_CLIENT_SECRET, time.strftime("%Y%m%d"))
    venue_list = []

    data = requests.get(url).json()
    for i in range(0, len(data['response']['groups'][0]['items'])):
        try:
            item = data['response']['groups'][0]['items'][i]
            venue = item['venue']
            venue_list.append(
                Business(venue['name'], venue['location']['address'],
                         venue['rating'], venue['ratingSignals'],
                         (venue['location']['lat'], venue['location']['lng'])))
        except:
            pass

    return venue_list
Example #14
0
    def get(self):

        title = '首页'

        username = self.get_secure_cookie('uname')

        subject_list = ()
        type_list = ()
        subject_list = Business.q_subject_list()
        type_list = Business.q_type_list()

        self.render('index.html',
                    title=title,
                    username=username,
                    type_list=type_list,
                    subject_list=subject_list)
Example #15
0
    def post(self):

        if 'oldid' not in self.request.arguments.keys():
            self.write('no')
            return
        else:
            oldid = int(''.join(self.request.arguments['oldid']))

        if 'newid' not in self.request.arguments.keys():
            self.write('no')
            return
        else:
            newid = int(''.join(self.request.arguments['newid']))

        if 'verify' not in self.request.arguments.keys():
            self.write('no')
            return
        else:
            verify = int(''.join(self.request.arguments['verify']))

        try:
            username = self.get_secure_cookie('uname')

            if Business.verify(username, oldid, newid, verify):
                self.write('ok')
            else:
                self.write('no')

        except DBException as e:
            self.write('no')
            return
Example #16
0
    def _new_question(data):

        for i in range(1):

            mysql = Mysql()

            try:
                mysql.connect_master()

                search_sql = "select id,json,subject,type from entity_question_new where oldid = %(oldid)d;"
                if 0 == mysql.query(search_sql, oldid=int(data)):
                    return None
                else:
                    question_set = mysql.fetch()

            except DBException as e:
                break

        newid = question_set[0]
        question_json = question_set[1]
        question_subject = question_set[2]
        question_type = question_set[3]

        new_question_dict = {}
        new_question_dict['q_new_id'] = newid
        new_question_dict['new_question'], new_question_dict[
            'blank_num'] = Business.q_json_parse(question_type, question_json)
        new_question_dict['subject'] = question_subject
        #print new_question_dict
        return new_question_dict
Example #17
0
    def post(self):

        if 'mark' not in self.request.arguments.keys():
            self.write('no')
            return
        else:
            mark = int(''.join(self.request.arguments['mark']))

        if 'oldid' not in self.request.arguments.keys():
            self.write('no')
            return
        else:
            oldid = int(''.join(self.request.arguments['oldid']))

        if 'newid' not in self.request.arguments.keys():
            self.write('no')
            return
        else:
            newid = int(''.join(self.request.arguments['newid']))

        try:
            if Business.q_mark(oldid, newid, mark) is not None:
                self.write('ok')

        except DBException as e:
            self.write('no')
            return
Example #18
0
def search(lat, lng, distance):
    """
    Searches the Yelp API (Max Limit = 20)

    :param lat: Latitude of the request
    :param long: Longitude of the request
    :param distance: Distance to search (meters)
    :returns: List of retrieved businesses
    """

    params = {}
    params['term'] = 'nightlife,night_club,restaurant'
    params['ll'] = '{},{}'.format(lat, lng)
    params['radius_filter'] = distance

    session = rauth.OAuth1Session(consumer_key=CONSUMER_KEY,
                                  consumer_secret=CONSUMER_SECRET,
                                  access_token=TOKEN,
                                  access_token_secret=TOKEN_SECRET)

    request = session.get('https://api.yelp.com/v2/search', params=params)
    data = request.json()
    session.close()

    business_list = []
    for business in data['businesses']:
        business_list.append(
            Business(business['name'],
                     business['location']['display_address'][0],
                     business['rating'], business['review_count'], 'N/A'))
    return business_list
Example #19
0
    def __init__(self, redis, features={}):
        Generator.__init__(self, redis, features)
        self.logger = logging.getLogger(__name__)

        for field in ['contact', 'npc']:
            if not hasattr(self, field):
                setattr(self, field, NPC(self.redis))
        if not hasattr(self, 'business'):
            setattr(self, 'business', Business(self.redis))

        if not hasattr(self, 'text'):

            for field in ['hook', 'request']:
                if hasattr(self, field):
                    self.template = getattr(self, field) + ' ' + self.template

            for field in ['requirement', 'disclaimer', 'payment']:
                if hasattr(self, field):
                    self.template = self.template + ' ' + getattr(self, field)

            self.template = self.template + ' Contact ' + self.contact.name.fullname
            self.template = self.template + ' at the ' + self.business.name.fullname
            if hasattr(self, 'detail'):
                self.template = self.template + ' ' + self.detail

            self.template += '.'

            self.text = self.render_template(self.template)
            self.text = self.render_template(self.text)
        self.text = self.text[0].capitalize() + self.text[1:]
Example #20
0
	def post(self):

		if 'oldid' not in self.request.arguments.keys():
                        self.write('no')
			return
                else:
			oldid= int(''.join(self.request.arguments['oldid']))

		if 'newid' not in self.request.arguments.keys():
                        self.write('no')
			return
		else:
			newid= int(''.join(self.request.arguments['newid']))

		if 'verify' not in self.request.arguments.keys():
                        self.write('no')
			return
		else:
			verify= int(''.join(self.request.arguments['verify']))

		try: 
			username = self.get_secure_cookie('uname')

			if Business.verify(username,oldid,newid,verify):
				self.write('ok')
			else:
				self.write('no')	

		except DBException as e:
			self.write('no')
			return
Example #21
0
	def post(self):

		if 'mark' not in self.request.arguments.keys():
			self.write('no')
			return
                else:
                        mark = int(''.join(self.request.arguments['mark']))
        
                if 'oldid' not in self.request.arguments.keys():
                        self.write('no')
			return
                else:
			oldid= int(''.join(self.request.arguments['oldid']))

		if 'newid' not in self.request.arguments.keys():
                        self.write('no')
			return
                else:
			newid= int(''.join(self.request.arguments['newid']))

		try:
			if Business.q_mark(oldid,newid,mark) is not None:
				self.write('ok')

		except DBException as e:
			self.write('no')
			return
Example #22
0
def search(lat, lng, distance):
    """
    Searches the Foursquare API (Max Limit = 50)

    :param lat: Latitude of the request
    :param long: Longitude of the request
    :param distance: Distance to search (meters)
    :returns: List of retrieved venues
    """

    url = 'https://api.foursquare.com/v2/venues/explore?ll=%s,%s&intent=browse&radius=%s&limit=50&categoryId=%s&client_id=%s&client_secret=%s&v=%s' % (
        lat, lng, distance, CATEGORY_ID, CLIENT_ID, CLIENT_SECRET,
        time.strftime("%Y%m%d"))
    venue_list = []

    try:
        data = make_request(url)

        for item in data['response']['groups'][0]['items']:
            venue = item['venue']
            venue_list.append(
                Business(venue['name'], venue['location']['address'],
                         venue['rating'], venue['ratingSignals'],
                         venue['stats']['checkinsCount']))
    except Exception, e:
        print e
Example #23
0
	def _new_question(data):
	
		for i in range(1):
		
			mysql = Mysql()
			
			try:
				mysql.connect_master()
				
				search_sql = "select id,json,subject,type from entity_question_new where oldid = %(oldid)d;"
				if 0 == mysql.query(search_sql,oldid = int(data)):	
					return None
				else:
					question_set = mysql.fetch()

			except DBException as e:
				break

		newid = question_set[0]
		question_json = question_set[1]
		question_subject = question_set[2]
		question_type = question_set[3]

		new_question_dict = {}
		new_question_dict['q_new_id'] = newid
		new_question_dict['new_question'],new_question_dict['blank_num'] = Business.q_json_parse(question_type,question_json)
		new_question_dict['subject'] = question_subject
		#print new_question_dict
		return new_question_dict
Example #24
0
	def post(self):

		if 'username' not in self.request.arguments.keys():
                        self.write('no')
			return
                else:
			username = ''.join(self.request.arguments['username'])

		if 'password' not in self.request.arguments.keys():
                        self.write('no')
			return
		else:
			password = ''.join(self.request.arguments['password'])

		try:
			if Business.check_user(username,password):
				self.set_secure_cookie('uname',username,expires_days = None)
				self.write('ok')
			
			else:
				self.write('no')
		except DBException:
			
			self.write('no')
			return 
Example #25
0
def get_business_info(query):
    # create url for API request
    api_url = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json"
    response = requests.get(api_url + "?input=" + query +
                            "&inputtype=textquery&key=" + api_key +
                            "&fields=name,formatted_address,place_id")
    if response.status_code != 200:
        raise ApiError("An error with status code {} occurred".format(
            response.status_code))
    else:
        json_response = response.json()  # store API info in business object
        print(json_response)
        business = Business()
        # TODO: throw appropriate exception if daily request quota for this API is reached
        business.name = json_response["candidates"][0]["name"]
        business.location = json_response["candidates"][0]["formatted_address"]
        business.place_id = json_response["candidates"][0]["place_id"]
        return business
Example #26
0
 def test_login_store2(self):
     wd = self.wd
     self.open_home_page(wd)
     self.login(wd,
                Credentional(username="******", password="******"))
     self.add_company(
         wd,
         Business(inn="222222222222",
                  ogrn="012345678912345",
                  phone="+71234567799",
                  email="*****@*****.**"))
     self.logout(wd)
Example #27
0
    def Connect(self):
        # configure how many client the server can listen simultaneously
        print("server is started and listening on port >>>>>>>>", self.port)
        self.server_socket.listen(5)
        conn, address = self.server_socket.accept()
        print("Connection from: " + str(address))

        while True:
            print("Looping while loop")
            data = conn.recv(1024).decode()
            if not data:
                # if data is not received break
                break
            print("Country Selected : ", data)
            scrape = Scrape()
            scrape.data_list()
            business = Business()
            country_data = business.countryData(data)
            print(type(country_data))
            msg = pickle.dumps(country_data)
            print("done pickling")
            conn.send(msg)
            print("DATA SENT TO THE CLIENT.... ")
Example #28
0
 def defineStatus(self):
     while True:
         print 'Aguardando conexao'
         con, cliente = self.tcpconn.accept()
         print 'Concetado por', cliente
         while True:
             msg = con.recv(1024)
             if not msg: break
             print cliente, msg
             jsonstatus = Business.Business().getStatus(int(msg))
             print jsonstatus
         print 'Finalizando conexao do cliente', cliente
         con.close()
         return msg
Example #29
0
class BusinessTest(unittest.TestCase):
    def setUp(self):
        self.business = Business()
        self.app = app.test_client()
        # self.businesscreds = {
        # 			'id': 1,
        # 			'name':'tuskys',
        # 			'location':'nairobi',
        # 			'category':'supermarket'
        # 			# 'createdby':'*****@*****.**'
        # }

    def test_register_business(self):
        response = self.app.post(
            '/api/v1/addbusiness',
            # data=json.dumps(self.businesscreds),
            headers={'Content-Type': 'application/json'})
        self.assertEqual(response.status_code, 201)
        self.assertIn('business created successfully', str(response.data))

    def test_list_business(self):
        response = self.app.post(
            '/api/v1/business',
            # data=json.dumps(self.businesscreds),
            headers={'Content-Type': 'application/json'})
        response = self.app.get('/api/v1/business')

        self.business.list_business = [{
            'createdby': '*****@*****.**',
            'name': 'biz',
            'location': 'nairobi',
            'category': 'tech'
        }]
        result = self.business.list_business
        value = self.business.list_allbusiness()
        self.assertEqual(result, value)
        # self.assertEqual(response.status_code,200)

    def test_add_empty_business_name(self):
        response = self.app.post('api/v1/addbusiness',
                                 data=dict(name="",
                                           location="nairobi",
                                           category="tech"))
        self.assertEqual(response.status_code, 401)
        message = json.loads(response.data.decode("UTF-8"))
        self.assertIn("Business name cannot be empty", message['message'])
Example #30
0
def search(lat, lng, distance, query):
    """
    Searches the Yelp API (Max Limit = 20)

    :param lat: Latitude of the request
    :param long: Longitude of the request
    :param distance: Distance to search (meters)
    :param query: The niche, i.e. restaurants, bars, etc
    :returns: List of retrieved businesses
    """

    payload = {
        'grant_type': 'client_credentials',
        'client_id': Y_ID,
        'client_secret': Y_S
    }

    token = requests.post('https://api.yelp.com/oauth2/token',
                          params=payload).json()["access_token"]
    headers = {'Authorization': 'Bearer ' + token}

    params = {}
    params['term'] = query
    params['longitude'] = lng
    params['latitude'] = lat
    params['radius_filter'] = distance
    data = requests.get("https://api.yelp.com/v3/businesses/search",
                        params=params,
                        headers=headers).json()

    business_list = []

    for i in range(0, 5):
        try:
            business = data['businesses'][i]
            business_list.append(
                Business(business['name'],
                         business['location']['display_address'][0],
                         business['rating'], business['review_count'],
                         (business["coordinates"]["latitude"],
                          business["coordinates"]["longitude"])))
        except:
            pass

    return business_list
Example #31
0
def search_place(place_id):
    """
    Searches Google for a specific Place

    :param id: Google Place ID
    :returns: Business object
    """
    url = PLACE_URL.format(place_id, G_API_KEY)
    data = requests.get(url).json()
    place = data['result']
    try:
        return Business(place['name'],
                        place['formatted_address'].split(',')[0],
                        place['rating'], len(place['reviews']),
                        (place["geometry"]["location"]["lat"],
                         place["geometry"]["location"]["lng"]))
    except:
        pass
Example #32
0
def search_place(place_id):
    """
    Searches Google for a specific Place

    :param id: Google Place ID
    :returns: Business object
    """

    url = PLACE_URL.format(place_id, GOOGLE_API_KEY)

    try:
        data = make_request(url)

        place = data['result']
        return Business(place['name'],
                        place['formatted_address'].split(',')[0],
                        place['rating'], place['user_ratings_total'], 'N/A')
    except Exception, e:
        print e
Example #33
0
    def __init__(self, redis, features={}):
        Generator.__init__(self, redis, features)
        self.logger = logging.getLogger(__name__)
        if not hasattr(self, 'region'):
            print "noregion!!!"
            self.region = region.Region(self.redis)

        self.gatheringplace = Business(self.redis,
                                       {'kind': 'bus_' + self.gatheringplace})
        if not hasattr(self, 'leader'):
            self.leader = leader.Leader(self.redis, {"location": self})
            #self.leader = Leader(self.redis)

        if not hasattr(self, 'name'):
            self.name = Name(self.redis, 'city')

        self.citizen = NPC(self.redis)

        self.calculate_population()
        self.calculate_racial_breakdown()
        self.select_subraces()
Example #34
0
    def new_game(self):
        # Create new city
        self.city = City()
        self.city.generate_name()
        self.city.generate_districts()

        # Generate AI companies
        for i in xrange(0, randrange(10, 20)):
            b = Business(self)
            b.starting_funds()
            b.randomize_production(self.industries, self.resources)
            b.generate_name()
            b.district = choice(self.city.districts.keys())
            # self.city.districts[b.district].companies.append(b)
            self.ai_companies.append(b)

            # for i in self.ai_companies:
            # 	print i.name, i.money, i.producing, i.district

        self.player.money = 1000000

        self.commands.show_city(None)
        self.update_options(self.menus["city_overview_menu"])
Example #35
0
def getBusinesses():

    ret = []
    with open("data/edinburgh_restaurants.json") as f:
        data = f.readlines()

    data = map(lambda x: x.rstrip(), data)
    data_json_str = "[" + ','.join(data) + "]"
    data_df = pd.read_json(data_json_str)
    for i in range(0, data_df.shape[0]):
        datai = data_df.iloc[i]
        b = Business()
        b.setID(datai["business_id"])
        b.setReviewCount(datai["review_count"])
        ret.append(b)

    return ret
Example #36
0
	def post(self):
		
		for i in range(1):

			LOG.info('API IN[%s]' % (self.__class__.__name__))
                        LOG.info('PARAMETER IN[%s]' % self.request.arguments)

                        ret = {'code':'','message':''}

                        essential_keys = set(['name','timestamp','secret'])

                        if Base.check_parameter(set(self.request.arguments.keys()),essential_keys):
                                ret['code'] = 1
                                ret['message'] = 'invalid parameter'
				LOG.error('ERROR[in parameter invalid]')
                                break
			
			group_name = ''.join(self.request.arguments['name'])
			timestamp = ''.join(self.request.arguments['timestamp'])
			secret = ''.join(self.request.arguments['secret'])

			if Base.empty(group_name) or Base.empty(timestamp) or Base.empty(secret):
				ret['code'] = 1
				ret['message'] = 'invalid parameter'
				LOG.error('ERROR[parameter empty]')
				break

			key = group_name + timestamp;
			secret_key = sha1(key).hexdigest()

			if secret == secret_key:
				if Business.group_name_exist(group_name):
					ret['code'] = 6
					ret['message'] = 'key exsit'
					LOG.error('ERROR[group exist]')
					break

				configer = Configer()
				remote_host = configer.get_configer('REMOTE','host')
				remote_port = configer.get_configer('REMOTE','port')
				remote_uri = configer.get_configer('REMOTE','uri')

				remote_url = "http://%s:%s/%s" % (remote_host,remote_port,remote_uri)
				
				token = self.get_cookie("teacher_id")
				LOG.info('TOKEN[%s]' % token)

				if token is None:
					ret['code'] = 6
					ret['message'] = 'invalid token'
					LOG.error('ERROR[token empty]')
					break

				post_data = {'token' : token}
				
				client = httpclient.AsyncHTTPClient()
				response = yield gen.Task(client.fetch,remote_url,method = 'POST',body = urllib.urlencode(post_data))
				#response = Http.post(remote_url,post_data)
				encode_body = json.loads(response.body)

				if 0 == encode_body['code'] or 2 == encode_body['code']:
					ret['code'] = 7
					ret['message'] = 'invalid token'
					LOG.error('ERROR[token not exist]')
					break

				if 1 == encode_body['code']:
					subject_id = encode_body['subject_id']
					grade_id = encode_body['grade_id']
					system_id = encode_body['system_id']
					org_type = encode_body['org_type']				

					db = Mysql()
			
					group_sql = "insert into entity_group (name,system_id) values ('%(group_name)s',%(system_id)d);"

					try:
						db.connect_master()
						group_res = db.query(group_sql,group_name = group_name,system_id = system_id)

						group_sql = db.get_last_sql()
						group_id = db.get_last_id()
						LOG.info('SQL[%s] - RES[%s] - INS[%d]' % (group_sql,group_res,group_id))
					
					except DBException as e:
						ret['code'] = 3
						ret['message'] = 'server error'
						LOG.error('ERROR[mysql error]')
						break

				else:
					ret['code'] = 3 
					ret['message'] = 'server error'
					LOG.error('ERROR[remote error]')
					break

				ret['code'] = 0
				ret['message'] = 'success'
				break				
			else:
				ret['code'] = 4
				ret['message'] = 'secure key error'
				LOG.error('ERR[secure key error]') 
				break

		self.write(json.dumps(ret))
		self.finish()
		LOG.info('PARAMETER OUT[%s]' % ret)
		LOG.info('API OUT[%s]' % (self.__class__.__name__))
Example #37
0
    else:
        json_response = response.json()  # store API info in business object
        print(json_response)
        business = Business()
        # TODO: throw appropriate exception if daily request quota for this API is reached
        business.name = json_response["candidates"][0]["name"]
        business.location = json_response["candidates"][0]["formatted_address"]
        business.place_id = json_response["candidates"][0]["place_id"]
        return business


# Takes in place_id parameter and returns a URL to the specified place in google maps
# "https://www.google.com/maps/search/?api=1&query=Google&query_place_id=ChIJN1t_tDeuEmsRUsoyG83frY4"
# Note: Maps URLs have a character limit of 2048 characters
# TODO: Add validation for character limit
def get_maps_url(place_id):
    query = ""  # temp query, add as param later
    maps_url = "https://www.google.com/maps/search/?api=1&query=" + query + "&query_place_id=" + place_id
    return maps_url


# Temporary data for testing (since maps API has a daily request quota of about 5)
business = Business()
business.name = "200 Waterloo Ave"
business.location = "200 Waterloo Ave, Guelph, ON N1H 3J5, Canada"
business.place_id = "ChIJn_pSxreaK4gRBaqeg1MbXa8"

# business = get_business_info("200 Waterloo Ave")
print(get_maps_url(business.place_id))
business = get_business_info("")
print(business.name + "\n" + business.location + "\n" + business.place_id)
Example #38
0
	def _q_subject_filter(self,data):

		filted_data = data
		#{'1' : "数学" ,"2" : "语文","3" : "英语","4" : "历史"}[data]

		if 'page' not in self.request.arguments.keys():
			pid = 0
		else:
			pid = int(''.join(self.request.arguments['page']))

		num = Business.q_subject_filter_num(filted_data)

		if 0 == num:
			self.write("没有此类型题")
			return

		#pid = self.get_secure_cookie("pid")

		#print "当前PID %s" % pid
		'''
		if pid is None:
			#self.set_secure_cookie("pid","0",expires_days = None)
			pid = 0 
		else:
			pid = int(pid)
		'''

		#self.set_secure_cookie("data",filted_data,expires_days = None)
		#self.set_secure_cookie("type","3",expires_days = None)

		filted_set = Business.q_subject_filter(filted_data,pid,1)

		#self.set_secure_cookie("pid",str(pid),expires_days = None)

		qid = filted_set[0][0]
		subject = filted_set[0][1]

		username = self.get_secure_cookie('uname')

		index_dict = {'username':username,'title' : '新旧题对比展示','subject' : subject}

		old_dict = self._old_question(qid)

		combine_dict = dict(index_dict,**old_dict)
		
		new_dict = self._new_question(qid)

		mark_list = Business.q_mark_list()
		
		mark_dict = {'mark_list' : mark_list}

		combine_dict = dict(combine_dict,**mark_dict)

		front_url = r'href = /page?type=3&data=%s&page=%d' % (filted_data,pid-1)
		next_url = r'href = /page?type=3&data=%s&page=%d' % (filted_data,pid+1)

		page_dict = {"front_is_able" : "","next_is_able" : "","front" : front_url,"next" : next_url}

		if pid >= num - 1:
			#self.set_secure_cookie("pid","0")
			page_dict["next_is_able"] = "disabled"
			page_dict["next"] = ""

		if 0 >= pid:
			page_dict["front_is_able"] =  "disabled"
			page_dict["front"] = ""

		combine_dict = dict(combine_dict,**page_dict)

		combine_dict = dict(combine_dict,**new_dict)

		systematics_list = Business.get_systematics(qid)
		systematics_dict = {'systematics_list' : systematics_list}

		combine_dict = dict(combine_dict,**systematics_dict)

		self.render("new_old_question_show.html",**combine_dict)
Example #39
0
    def post(self):

        for i in range(1):

            LOG.info('API IN[%s]' % (self.__class__.__name__))
            LOG.info('PARAMETER IN[%s]' % self.request.arguments)

            ret = {'code': '', 'message': ''}

            essential_keys = set(['id', 'name'])

            if Base.check_parameter(set(self.request.arguments.keys()),
                                    essential_keys):
                ret['code'] = 1
                ret['message'] = '无效参数'
                LOG.error('ERROR[in parameter invalid]')
                break

            group_id = ''.join(self.request.arguments['id'])
            group_name = ''.join(self.request.arguments['name'])

            if Base.empty(group_id) or Base.empty(group_name):
                ret['code'] = 1
                ret['message'] = '无效参数'
                LOG.error('ERROR[parameter empty]')
                break

            configer = Configer()
            remote_host = configer.get_configer('REMOTE', 'host')
            remote_port = configer.get_configer('REMOTE', 'port')
            remote_uri = configer.get_configer('REMOTE', 'uri')

            remote_url = "http://%s:%s/%s" % (remote_host, remote_port,
                                              remote_uri)

            token = self.get_cookie("teacher_id")
            LOG.info('TOKEN[%s]' % token)

            if token is None:
                ret['code'] = 6
                ret['message'] = '无效参数'
                LOG.error('ERROR[token empty]')
                break

            post_data = {'token': token}

            client = httpclient.AsyncHTTPClient()
            response = yield gen.Task(client.fetch,
                                      remote_url,
                                      method='POST',
                                      body=urllib.urlencode(post_data))
            #response = Http.post(remote_url,post_data)

            LOG.info('REMOTE RES CODE[%d]' % response.code)

            if 200 == response.code:
                encode_body = json.loads(response.body)

                if 0 == encode_body['code'] or 2 == encode_body['code']:
                    ret['code'] = 7
                    ret['message'] = '无效参数'
                    LOG.error('ERROR[token not exist]')
                    break

                if 1 == encode_body['code']:
                    subject_id = encode_body['subject_id']
                    grade_id = encode_body['grade_id']
                    system_id = encode_body['system_id']
                    org_type = encode_body['org_type']

                    if Business.group_name_exist(group_name, system_id):
                        ret['code'] = 6
                        ret['message'] = '组名已存在'
                        LOG.error('ERROR[group exist]')
                        break

                    db = Mysql()

                    group_sql = "update entity_group set name='%(group_name)s' where id=%(group_id)d and system_id=%(system_id)d;"

                    try:
                        db.connect_master()
                        group_res = db.query(group_sql,
                                             group_name=group_name,
                                             group_id=int(group_id),
                                             system_id=int(system_id))

                        if group_res is False:
                            ret['code'] = 7
                            ret['message'] = '无效参数'
                            LOG.error('ERROR[group not exist]')
                            break

                        group_sql = db.get_last_sql()
                        group_id = db.get_last_id()
                        LOG.info('SQL[%s] - RES[%s] - INS[%d]' %
                                 (group_sql, group_res, group_id))

                    except DBException as e:
                        ret['code'] = 3
                        ret['message'] = '服务器错误'
                        LOG.error('ERROR[mysql error]')
                        break

                else:
                    ret['code'] = 3
                    ret['message'] = '服务器错误'
                    LOG.error('ERROR[remote error]')
                    break

            else:
                ret['code'] = 3
                ret['message'] = '服务器错误'
                LOG.error('ERROR[remote error]')
                break

            ret['code'] = 0
            ret['message'] = 'success'
            break

        self.write(json.dumps(ret))
        self.finish()
        LOG.info('PARAMETER OUT[%s]' % ret)
        LOG.info('API OUT[%s]' % (self.__class__.__name__))
Example #40
0
 def __init__(self, ip, port):
     Control.control_clients.add(self)
     Business.__init__(self, 'control', ip, port)
Example #41
0
from util import next_weekday

# Opening hours for each week day. If not specified, it is considered closed
days = [
    # Standard days with fixed opening hours
    Day(Days.MONDAY, [['09:00', '14:00'], ['14:45', '18:00']]),
    Day(Days.TUESDAY, [['09:00', '14:00'], ['14:45', '18:00']]),
    Day(Days.WEDNESDAY, [['09:00', '14:00'], ['14:45', '18:00']]),
    Day(Days.THURSDAY, [['09:00', '14:00'], ['14:45', '18:00']]),
    Day(Days.FRIDAY, [['09:00', '14:00'], ['14:45', '16:45']]),
    Day(Days.SATURDAY, [['09:00', '10:00'], ['11:00', '12:00'], ['13:00', '14:00'], ['15:00', '16:45']]),
]


# Create a new Business instance
business = Business(days)

if False:
    nextDate = business.closest(datetime.datetime(2015, 5, 11, 10, 0))
    print nextDate

if False:
    start = datetime.datetime(2015, 5, 11, 10, 0)
    end = datetime.datetime(2015, 5, 14, 10, 0)

    dates = business.timeline(start, end, interval=1);
    print dates

#
# datetime.datetime(2015, 8, 7) == Friday
# Both values in the same day
 def test_create_business(self):
     business = Business()
     response = business.create_business("andela", "TRM")
     self.assertEqual(response["message"], "Business created successfully")
Example #43
0
	def post(self):
		
		for i in range(1):

			LOG.info('API IN[%s]' % (self.__class__.__name__))
                        LOG.info('PARAMETER IN[%s]' % self.request.arguments)

                        ret = {'code':'','message':''}

                        essential_keys = set(['id','name'])

                        if Base.check_parameter(set(self.request.arguments.keys()),essential_keys):
                                ret['code'] = 1
                                ret['message'] = '无效参数'
				LOG.error('ERROR[in parameter invalid]')
                                break

			group_id = ''.join(self.request.arguments['id'])
			group_name = ''.join(self.request.arguments['name'])

			if Base.empty(group_id) or Base.empty(group_name):
				ret['code'] = 1
				ret['message'] = '无效参数'
				LOG.error('ERROR[parameter empty]')
				break

			configer = Configer()
			remote_host = configer.get_configer('REMOTE','host')
			remote_port = configer.get_configer('REMOTE','port')
			remote_uri = configer.get_configer('REMOTE','uri')

			remote_url = "http://%s:%s/%s" % (remote_host,remote_port,remote_uri)
			
			token = self.get_cookie("teacher_id")
			LOG.info('TOKEN[%s]' % token)

			if token is None:
				ret['code'] = 6
				ret['message'] = '无效参数'
				LOG.error('ERROR[token empty]')
				break

			post_data = {'token' : token}
			
			client = httpclient.AsyncHTTPClient()
			response = yield gen.Task(client.fetch,remote_url,method = 'POST',body = urllib.urlencode(post_data))
			#response = Http.post(remote_url,post_data)

			LOG.info('REMOTE RES CODE[%d]' % response.code)

			if 200 == response.code:
				encode_body = json.loads(response.body)

				if 0 == encode_body['code'] or 2 == encode_body['code']:
					ret['code'] = 7
					ret['message'] = '无效参数'
					LOG.error('ERROR[token not exist]')
					break

				if 1 == encode_body['code']:
					subject_id = encode_body['subject_id']
					grade_id = encode_body['grade_id']
					system_id = encode_body['system_id']
					org_type = encode_body['org_type']				
					
					if Business.group_name_exist(group_name,system_id):
						ret['code'] = 6
						ret['message'] = '组名已存在'
						LOG.error('ERROR[group exist]')
						break

					db = Mysql()
			
					group_sql = "update entity_group set name='%(group_name)s' where id=%(group_id)d and system_id=%(system_id)d;"

					try:
						db.connect_master()
						group_res = db.query(group_sql,group_name = group_name,group_id = int(group_id),system_id = int(system_id))

						if group_res is False:
							ret['code'] = 7 
							ret['message'] = '无效参数'
							LOG.error('ERROR[group not exist]')
							break	

						group_sql = db.get_last_sql()
						group_id = db.get_last_id()
						LOG.info('SQL[%s] - RES[%s] - INS[%d]' % (group_sql,group_res,group_id))
					
					except DBException as e:
						ret['code'] = 3
						ret['message'] = '服务器错误'
						LOG.error('ERROR[mysql error]')
						break

				else:
					ret['code'] = 3 
					ret['message'] = '服务器错误'
					LOG.error('ERROR[remote error]')
					break

			else:
				ret['code'] = 3 
				ret['message'] = '服务器错误'
				LOG.error('ERROR[remote error]')
				break

			ret['code'] = 0
			ret['message'] = 'success'
			break				

		self.write(json.dumps(ret))
		self.finish()
		LOG.info('PARAMETER OUT[%s]' % ret)
		LOG.info('API OUT[%s]' % (self.__class__.__name__))
Example #44
0
	def get(self):

		if 'page' not in self.request.arguments.keys():
			pid = 0
		else:
			pid = int(''.join(self.request.arguments['page']))
	
		if 'type' not in self.request.arguments.keys():
			filted_type = '1'
		else:
			filted_type = ''.join(self.request.arguments['type'])

		if 'data' not in self.request.arguments.keys():
			filted_data = '1'
		else:
			filted_data = urllib.unquote(''.join(self.request.arguments['data']))

		access = {'2' : 'q_type_filter','3' : 'q_subject_filter'}[filted_type]

		filted_set = getattr(Business,access)(filted_data,pid,1)

                qid = filted_set[0][0]
		subject	= filted_set[0][1]

		username = self.get_secure_cookie('uname')

                index_dict = {'username':username,'title' : '新旧题对比展示','subject' : subject}

                old_dict = Search._old_question(qid)

                combine_dict = dict(index_dict,**old_dict)

		num_access = {'2' : 'q_type_filter_num','3' : 'q_subject_filter_num'}[filted_type]
       
                num = getattr(Business,num_access)(filted_data)
		
		mark_list = Business.q_mark_list()
		
		mark_dict = {'mark_list' : mark_list}

		combine_dict = dict(combine_dict,**mark_dict)

		new_dict = Search._new_question(qid)

		front_url = r'href = /page?type=%s&data=%s&page=%d' % (filted_type,filted_data,pid-1)
		next_url = r'href = /page?type=%s&data=%s&page=%d' % (filted_type,filted_data,pid+1)

		page_dict = {"front_is_able" : "","next_is_able" : "","front" : front_url,"next" : next_url}

		#self.set_secure_cookie("pid",str(pid),expires_days = None)

                if pid >= num-1:
                        #self.set_secure_cookie("pid","0")
                        page_dict["next_is_able"] = "disabled"
			page_dict["next"] = ""

                if 0 >= pid:
                        page_dict["front_is_able"] =  "disabled"
			page_dict["front"] = ""

                combine_dict = dict(combine_dict,**page_dict)

		combine_dict = dict(combine_dict,**new_dict)

		systematics_list = Business.get_systematics(qid)
		systematics_dict = {'systematics_list' : systematics_list}
		LOG.info('haha%s' % systematics_dict)
		combine_dict = dict(combine_dict,**systematics_dict)

                self.render("new_old_question_show.html",**combine_dict)
Example #45
0
	def get(self):

		for i in range(1):
			self.set_header("charset","utf-8"); 

			LOG.info('API IN[%s]' % (self.__class__.__name__))
                        LOG.info('PARAMETER IN[%s]' % self.request.arguments)

                        ret = {'code':'','message':'','group_list' : [],'default_num' : 0}

                        essential_keys = set(['timestamp','secret'])

                        if Base.check_parameter(set(self.request.arguments.keys()),essential_keys):
                                ret['code'] = 1
                                ret['message'] = '无效参数'
				LOG.error('ERR[in parameter invalid]') 
                                break
			
			timestamp = ''.join(self.request.arguments['timestamp'])
			secret = ''.join(self.request.arguments['secret'])

			if Base.empty(timestamp):
				ret['code'] = 1
				ret['message'] = '无效参数'
				LOG.error('ERROR[parameter empty]')
				break

			key = timestamp;
			secret_key = sha1(key).hexdigest()

			if secret == secret_key:
				configer = Configer()
				remote_host = configer.get_configer('REMOTE','host')
				remote_port = configer.get_configer('REMOTE','port')
				remote_uri = configer.get_configer('REMOTE','uri')

				remote_url = "http://%s:%s/%s" % (remote_host,remote_port,remote_uri)
				
				token = self.get_cookie("teacher_id")
				LOG.info('TOKEN[%s]' % token)

				if token is None:
					ret['code'] = 6
					ret['message'] = '无效参数'
					LOG.error('ERROR[token empty]')
					break

				post_data = {'token' : token}
				
				client = httpclient.AsyncHTTPClient()
				response = yield gen.Task(client.fetch,remote_url,method = 'POST',body = urllib.urlencode(post_data))
				#response = Http.post(remote_url,post_data)
				LOG.info('REMOTE RES CODE[%d]' % response.code)

				if 200 == response.code:
					encode_body = json.loads(response.body)

					if 0 == encode_body['code'] or 2 == encode_body['code']:
						ret['code'] = 7
						ret['message'] = '无效参数'
						LOG.error('ERR[token not exist]') 
						break

					if 1 == encode_body['code']:
						#subject_id = encode_body['subject_id']
						#grade_id = encode_body['grade_id']
						system_id = encode_body['system_id']
						#org_type = encode_body['org_type']				
					
						try:
							group_list,default_num = Business.get_group_list(system_id)
							
							if group_list is not False:
								ret['group_list'] = group_list
								ret['default_num'] = default_num				
						except DBException as e:
							ret['code'] = 3
							ret['message'] = '服务器错误'
							LOG.error('ERR[mysql error]') 
							break

					else:
						ret['code'] = 3 
						ret['message'] = '服务器错误'
						LOG.error('ERROR[remote error]')
						break
					
				else:
					ret['code'] = 3 
					ret['message'] = '服务器错误'
					LOG.error('ERROR[remote error]')
					break

				ret['code'] = 0
				ret['message'] = 'success'
				break
			else:
				ret['code'] = 4
				ret['message'] = 'secure key error'
				LOG.error('ERR[secure key error]') 
				break

		self.write(ret)
		self.finish()
		LOG.info('PARAMETER OUT[%s]' % ret)
		LOG.info('API OUT[%s]' % (self.__class__.__name__))
Example #46
0
	def post(self):
		
		for i in range(1):

			self.set_header("Access-Control-Allow-Origin", "*")

			LOG.info('API IN[%s]' % (self.__class__.__name__))
			LOG.info('PARAMETER IN[%s]' % self.request.arguments)
			
			ret = {'code':'','message':''}

			essential_keys = set(['json','html','topic','level','type','group','chapter','ref'])

			if Base.check_parameter(set(self.request.arguments.keys()),essential_keys):
				ret['code'] = 1
				ret['message'] = '无效参数'
				LOG.error('ERR[in parameter invalid]') 
				break

			question_json = ''.join(self.request.arguments['json'])
			question_html = ''.join(self.request.arguments['html'])
			question_topic = ''.join(self.request.arguments['topic'])
			question_level = ''.join(self.request.arguments['level'])
			question_type = ''.join(self.request.arguments['type'])
			question_group = ''.join(self.request.arguments['group'])
			question_chapter = ''.join(self.request.arguments['chapter'])
			ref = ''.join(self.request.arguments['ref'])


			if Business.is_level(question_level) is False:
				ret['code'] = 1
				ret['message'] = '无效参数'
				LOG.error('ERR[level is invalid]') 
				break

			try:
				#question_json = urllib.unquote(question_json)
				#question_json = question_json.replace("'","\"")
				encode_json = json.loads(question_json,encoding = 'utf-8')
				#question_html = urllib.unquote(question_html)
				#question_html = question_html.replace("'","\"")
				encode_html = json.loads(question_html,encoding = 'utf-8')

				LOG.info('Json Loads Successful')
				answer_num = 0
				
				if Base.empty(question_topic) and Base.empty(question_chapter):
					ret['code'] = 1
					ret['message'] = '无效参数'
					LOG.error('ERR[topic and chapter empty]') 
					break

				if Base.empty(question_group):
					ret['code'] = 1
					ret['message'] = '无效参数'
					LOG.error('ERR[group empty]') 
					break

				if Base.empty(question_topic) is False:
					topic_list = question_topic.split(',')

					for question_theme in topic_list:
						if Business.is_topic(question_theme) is False:
							ret['code'] = 1
							ret['message'] = '无效参数'
							LOG.error('ERR[topic %s invalid]' % question_theme) 
							break

				type_name =  Business.is_type(question_type)

				if type_name is False:
					ret['code'] = 1
					ret['message'] = '无效参数'
					LOG.error('ERR[type is invalid]') 
					break

				option_num = 0

				LOG.info('Json Parse Start')

				if type_name == '选择题'.decode('utf-8'):
					if 'answer' in encode_json.keys():
						answer_num = len(encode_json['answer'])
						option_num = len(encode_json['options'])

				if type_name == '填空题'.decode('utf-8'):
					if 'answer' in encode_json.keys():
							answer_num = max([int(group['index']) for group in encode_json['answer']])
				
				LOG.info('Json Parse End')

				if not Base.empty(question_chapter):
					if Business.chapter_id_exist(question_chapter) is False:
						ret['code'] = 1
						ret['message'] = '无效参数'
						LOG.error('ERR[seriess %s invalid]' % question_theme) 
						break
			except (ValueError,KeyError,TypeError):
				ret['code'] = 1
				ret['message'] = '无效参数'
				LOG.error('ERR[json format invalid]') 
				break

			except CKException: 
				ret['code'] = 3
				ret['message'] = '服务器错误'
				LOG.error('ERR[mysql exception]') 
				break

			key = question_topic + question_level + question_type + question_group
			secret_key = hashlib.sha1(key).hexdigest()

			qiniu = QiniuWrap()

			json_key = 'tmp_' + secret_key + '.json'
			if not qiniu.upload_data("temp",json_key,question_json):
				ret['code'] = 4
				ret['message'] = '服务器错误'
				LOG.error('ERR[json upload  qiniu exception]') 
				break
			
			html_key = 'tmp_' + secret_key + '.html'
			if not qiniu.upload_data("temp",html_key,question_html):
				ret['code'] = 4
				ret['message'] = '服务器错误'
				LOG.error('ERR[html upload  qiniu exception]') 
				break

			configer = Configer()
			remote_host = configer.get_configer('REMOTE','host')
			remote_port = configer.get_configer('REMOTE','port')
			remote_uri = configer.get_configer('REMOTE','uri')
			remote_timeout = configer.get_configer('REMOTE','timeout')
			
			remote_url = "http://%s:%s/%s" % (remote_host,remote_port,remote_uri)

			token = self.get_cookie("teacher_id")
			LOG.info('TOKEN[%s]' % token)

			if token is None:
				ret['code'] = 6
				ret['message'] = 'token失效'
				LOG.error('ERROR[token empty]')
				break

			post_data = {'token' : token}

			client = httpclient.AsyncHTTPClient()
			response = yield gen.Task(client.fetch,remote_url,request_timeout = int(remote_timeout),method = 'POST',body = urllib.urlencode(post_data
))
			#response = Http.post(remote_url,post_data)

			if 200 == response.code:
				encode_body = json.loads(response.body,encoding = 'utf-8')

				if 0 == encode_body['code'] or 2 == encode_body['code']:
					ret['code'] = 7
					ret['message'] = 'token失效'
					LOG.error('ERR[token not exist]')
					break

				if 1 == encode_body['code']:
					subject_id = encode_body['subject_id']
					grade_id = encode_body['grade_id']
					system_id = encode_body['system_id']
					org_type = encode_body['org_type']


					if 0 != int(question_group):
						if Business.group_id_exist(question_group,system_id) is False:
							ret['code'] = 8
							ret['message'] = '无效参数'
							LOG.error('ERROR[group not exist]')
							break	

					db = Mysql()

					question_sql = "insert into entity_question (difficulty,question_docx,html,upload_time,update_time,question_type,subject_id,new_format,upload_id,upload_src,question_group,grade_id,state,is_single,question_type_id,answer_num,count_ref,paper_year,parent_question_id,count_options) values (%(level)d,'%(json)s','%(html)s',now(),now(),'%(type)s',%(subject_id)d,1,%(upload_id)d,%(upload_src)d,%(question_group)d,%(grade_id)d,'ENABLED',1,%(question_type_id)d,%(answer_num)d,0,0,0,%(count_options)d);"
					
					link_topic_sql = "insert into link_question_topic (question_id,topic_id) values (%(q_id)d,%(t_id)d);"

					link_chapter_sql = "insert into link_question_chapter (question_id,chapter_id) values (%(q_id)d,%(c_id)d);"

					try:
						db.connect_master()
						db.start_event()

						question_res = db.exec_event(question_sql,level = int(question_level),json = json_key,html = html_key,type = type_name,subject_id = int(subject_id),upload_id = int(system_id),upload_src = int(org_type),question_group = int(question_group),grade_id = int(grade_id),question_type_id = int(question_type),answer_num = answer_num,count_options = option_num)
						question_sql = db.get_last_sql()
						question_id = db.get_last_id()
						LOG.info('RES[%s] - INS[%d]' % (question_res,question_id))
				
						if Base.empty(question_topic) is False:
							topic_list = question_topic.split(',')
							for question_theme in topic_list:
								topic_res = db.exec_event(link_topic_sql,q_id = int(question_id),t_id = int(question_theme))
								topic_sql = db.get_last_sql()
								topic_id = db.get_last_id()
								LOG.info('RES[%s] - INS[%d]' % (topic_res,topic_id))

						if not Base.empty(question_chapter):
							chapter_res = db.exec_event(link_chapter_sql,q_id = int(question_id),c_id = int(question_chapter))
							chapter_sql = db.get_last_sql()
							chapter_id = db.get_last_id()
							LOG.info('RES[%s] - INS[%d]' % (chapter_res,chapter_id))
						
					except DBException as e:
						db.rollback()
						db.end_event()
						ret['code'] = 3
						ret['message'] = '服务器错误'
						LOG.error('ERR[insert mysql error]') 
						break

			else:
				ret['code'] = 3
				ret['message'] = '服务器错误'
				LOG.error('ERROR[remote error]')
				break
							
			mongo = Mongo()

			try:
				mongo.connect('resource')
				mongo.select_collection('mongo_question_json')
				json_id = mongo.insert_one({"content":encode_json,"question_id":question_id})
				LOG.info('MONGO[insert json] - DATA[%s] - INS[%s] - Question Id[%d]' % (json.dumps(encode_json),json_id,question_id))

				mongo.select_collection('mongo_question_html')
				html_id = mongo.insert_one({"content":encode_html,"question_id":question_id})
				LOG.info('MONGO[insert html] - DATA[%s] - INS[%s] - Question Id[%d]' % (json.dumps(encode_html),html_id,question_id))

			except DBException as e:
				db.rollback()
				db.end_event()
				ret['code'] = 3 
				ret['message'] = '服务器错误'
				LOG.error('ERR[mongo exception]') 
				break

			db.end_event()

			if int(ref):
				doit = Doit()
				doit.local_img(str(question_id))
				LOG.info('Local Img [%s]' % str(question_id))

			ret['code'] = 0
			ret['message'] = 'success'
			ret['id'] = question_id

		LOG.info('PARAMETER OUT[%s]' % ret)
		LOG.info('API OUT[%s]' % (self.__class__.__name__))
		self.write(json.dumps(ret))
		self.finish()
Example #47
0
	def post(self):

		if 'oldid' not in self.request.arguments.keys():
                        self.write('no')
			return
                else:
			oldid = int(''.join(self.request.arguments['oldid']))

		if 'new_answer' not in self.request.arguments.keys():
                        self.write('no')
			return
		else:
			new_answer = ''.join(self.request.arguments['new_answer'])
		
		if 'sub_id' not in self.request.arguments.keys():
                        self.write('no')
			return
		else:
			sub_id = int(''.join(self.request.arguments['sub_id']))

		try: 
			question_json = Business.get_json_by_id(oldid)
			
			if question_json is False:
				self.write('no')
				return 
			
			encode_json = json.loads(question_json)
			
		except DBException as e:
			self.write('no')
			return

		#确定答案,题干
		if 0 == sub_id:
			encode_answer = encode_json['answer']
			encode_body = encode_json['body']
		else:
			encode_answer = encode_json['questions'][sub_id-1]['answer']
			encode_body = encode_json['questions'][sub_id-1]['body']

		#print encode_body

		new_answer_dict = {}
		new_answer_list = new_answer.split('|')

		current_index = 1

		old_blank_num = len(new_answer_list) - 1

		#填补答案索引
		for index,item in enumerate(encode_answer):
			if 'image' == item['type']:
				tmp_dict = {'index':current_index,'group':item}
				encode_answer[index] = tmp_dict
				current_index += 1

			if 'text' == item['type']:
				tmp_dict = {'index':current_index,'group':item}
				encode_answer[index] = tmp_dict
				current_index += 1

		for i in range(current_index,old_blank_num+1):
			encode_answer.append({"index":i,"group":{}})


		#print encode_answer

		#计算联合blank,并更新json
		new_blank_num = 0 
		start_point = 0
		union = 1
		union_flag = False
		empty_flag = False
		cur_index = 1
		union_dict = {}

		for no,new_answer in enumerate(new_answer_list):
			if Base.empty(new_answer) is False:
				index_answer = new_answer.split(',')
				answer_index = index_answer[0]
				answer_content = index_answer[1]

				if Base.empty(answer_content):
					union += 1
					empty_flag = True
					union_flag = False
					print '空'

				else:
					new_blank_num += 1
					union_flag = True
					empty_flag = False
					new_answer_dict[cur_index] = answer_content			
					cur_index += 1
					print '有'

			print union,union_flag,empty_flag,no
			if union > 1 and union_flag and empty_flag is False:
				#print "start_union%d" % start_point
				#print "union%d" % union

				union_index_list = [i+1 for i in range(start_point+1,no)]
				print union_index_list

				for j,item in enumerate(encode_body):
					for union_index in union_index_list:
						if 'blank' == item['type'] and union_index == item['value']:
							del encode_body[j]
							break		

					if 'blank' == item['type'] and start_point+1 == item['value']:
						print '进入1'
						encode_body[j]['union'] = union
						encode_body[j]['value'] = cur_index - 2
						print cur_index-1
				start_point = no
				union = 1
			
			elif union > 1 and no == old_blank_num-1:
				#print "start_union%d" % start_point
				#print "union%d" % union

				union_index_list = [i+1 for i in range(start_point+1,no+1)]
				print union_index_list

				for j,item in enumerate(encode_body):
					for union_index in union_index_list:
						if 'blank' == item['type'] and union_index == item['value']:
							del encode_body[j]
							break		
					#print start_point
					if 'blank' == item['type'] and start_point+1 == item['value']:
						print '进入2'
						encode_body[j]['union'] = union
						encode_body[j]['value'] = cur_index - 1
						print cur_index-1
				start_point = no
				union = 1

			if Base.empty(answer_content) is False:
				start_point = no
			
		#print encode_body
		#print union_index_list
		#print new_answer_dict
		#填写答案
		for index,answer in new_answer_dict.items():
			for item in encode_answer:
				if 'index' in item.keys() and index == item['index']:
					item['group']['type'] = 'text'
					item['group']['value'] = answer
					break

		for del_index in range(new_blank_num+1,old_blank_num+1):
			for p,item in enumerate(encode_answer):
				if'index' in item.keys() and  del_index == item['index']:
					del encode_answer[p]
					break

		#print encode_body

		#修改原始的json

		if 0 == sub_id:
			encode_json['body'] = encode_body
			encode_json['answer'] = encode_answer

		else:
			encode_json['questions'][sub_id-1]['body'] = encode_body
			encode_json['questions'][sub_id-1]['answer'] = encode_answer

		print encode_json
		#print '---'
		#print encode_answer
		#new_question_json = json.dumps(encode_json,ensure_ascii = False)
		new_question_json = json.dumps(encode_json)
		#print new_question_json
		'''
Example #48
0
 def on_close(self):
     Hancock.control_clients.remove(self)
     Business.on_close(self)
Example #49
0
from util import next_weekday

# Opening hours for each week day. If not specified, it is considered closed
days = [
    # Standard days with fixed opening hours
    Day(Days.MONDAY, [['09:00', '14:00'], ['14:45', '18:00']]),
    Day(Days.TUESDAY, [['09:00', '14:00'], ['14:45', '18:00']]),
    Day(Days.WEDNESDAY, [['09:00', '14:00'], ['14:45', '18:00']]),
    Day(Days.THURSDAY, [['09:00', '14:00'], ['14:45', '18:00']]),
    Day(Days.FRIDAY, [['09:00', '14:00'], ['14:45', '16:45']]),
    Day(Days.SATURDAY, [['09:00', '10:00'], ['11:00', '12:00'],
                        ['13:00', '14:00'], ['15:00', '16:45']]),
]

# Create a new Business instance
business = Business(days)

if False:
    nextDate = business.closest(datetime.datetime(2015, 5, 11, 10, 0))
    print nextDate

if False:
    start = datetime.datetime(2015, 5, 11, 10, 0)
    end = datetime.datetime(2015, 5, 14, 10, 0)

    dates = business.timeline(start, end, interval=1)
    print dates

#
# datetime.datetime(2015, 8, 7) == Friday
# Both values in the same day
Example #50
0
 def business(self):
     qry = Business.query(Business.admins == self.key)
     return qry.get()
Example #51
0
 def on_close(self):
     Business.on_close(self)
Example #52
0
    def get(self):

        for i in range(1):
            self.set_header("charset", "utf-8")

            LOG.info('API IN[%s]' % (self.__class__.__name__))
            LOG.info('PARAMETER IN[%s]' % self.request.arguments)

            ret = {
                'code': '',
                'message': '',
                'group_list': [],
                'default_num': 0
            }

            essential_keys = set(['timestamp', 'secret'])

            if Base.check_parameter(set(self.request.arguments.keys()),
                                    essential_keys):
                ret['code'] = 1
                ret['message'] = '无效参数'
                LOG.error('ERR[in parameter invalid]')
                break

            timestamp = ''.join(self.request.arguments['timestamp'])
            secret = ''.join(self.request.arguments['secret'])

            if Base.empty(timestamp):
                ret['code'] = 1
                ret['message'] = '无效参数'
                LOG.error('ERROR[parameter empty]')
                break

            key = timestamp
            secret_key = sha1(key).hexdigest()

            if secret == secret_key:
                configer = Configer()
                remote_host = configer.get_configer('REMOTE', 'host')
                remote_port = configer.get_configer('REMOTE', 'port')
                remote_uri = configer.get_configer('REMOTE', 'uri')

                remote_url = "http://%s:%s/%s" % (remote_host, remote_port,
                                                  remote_uri)

                token = self.get_cookie("teacher_id")
                LOG.info('TOKEN[%s]' % token)

                if token is None:
                    ret['code'] = 6
                    ret['message'] = '无效参数'
                    LOG.error('ERROR[token empty]')
                    break

                post_data = {'token': token}

                client = httpclient.AsyncHTTPClient()
                response = yield gen.Task(client.fetch,
                                          remote_url,
                                          method='POST',
                                          body=urllib.urlencode(post_data))
                #response = Http.post(remote_url,post_data)
                LOG.info('REMOTE RES CODE[%d]' % response.code)

                if 200 == response.code:
                    encode_body = json.loads(response.body)

                    if 0 == encode_body['code'] or 2 == encode_body['code']:
                        ret['code'] = 7
                        ret['message'] = '无效参数'
                        LOG.error('ERR[token not exist]')
                        break

                    if 1 == encode_body['code']:
                        #subject_id = encode_body['subject_id']
                        #grade_id = encode_body['grade_id']
                        system_id = encode_body['system_id']
                        #org_type = encode_body['org_type']

                        try:
                            group_list, default_num = Business.get_group_list(
                                system_id)

                            if group_list is not False:
                                ret['group_list'] = group_list
                                ret['default_num'] = default_num
                        except DBException as e:
                            ret['code'] = 3
                            ret['message'] = '服务器错误'
                            LOG.error('ERR[mysql error]')
                            break

                    else:
                        ret['code'] = 3
                        ret['message'] = '服务器错误'
                        LOG.error('ERROR[remote error]')
                        break

                else:
                    ret['code'] = 3
                    ret['message'] = '服务器错误'
                    LOG.error('ERROR[remote error]')
                    break

                ret['code'] = 0
                ret['message'] = 'success'
                break
            else:
                ret['code'] = 4
                ret['message'] = 'secure key error'
                LOG.error('ERR[secure key error]')
                break

        self.write(ret)
        self.finish()
        LOG.info('PARAMETER OUT[%s]' % ret)
        LOG.info('API OUT[%s]' % (self.__class__.__name__))
Example #53
0
    def __init__(self, ip, port):
        self._type = -1
        self._status = -1
        self._error = ''

        Business.__init__(self, 'forward', ip, port)
Example #54
0
    def post(self):

        self.set_header("Access-Control-Allow-Origin", "*")

        enter_func(self)

        if not set(['id', 'json', 'html', 'topic', 'level', 'type', 'group', 'chapter']).issubset(self.request.arguments.keys()):
            return leave_func(self, 1)

        theme         = self.request.arguments['topic'][0]
        type_id       = self.request.arguments['type'][0]
        level_id      = self.request.arguments['level'][0]
        group_id      = self.request.arguments['group'][0]
        chapter_id    = self.request.arguments['chapter'][0]
        question_id   = self.request.arguments['id'][0]
        question_json = self.request.arguments['json'][0]
        question_html = self.request.arguments['html'][0]

        try:
            if not (type_id.isdigit() and int(type_id) and level_id.isdigit() and int(level_id) and group_id.isdigit() and question_id.isdigit() and int(question_id) and theme + chapter_id and question_json and question_html):
                return leave_func(self, 1)
            if chapter_id and not chapter_id.isdigit():
                return leave_func(self, 1)

            if Business.is_level(level_id) is False:
                LOG.error('invalid level_id[%s]' % level_id)
                return leave_func(self, 1)

            try:
                #question_json = urllib.unquote(question_json)
                encode_json = {}
                encode_json['content'] = json.loads(question_json, encoding = 'utf-8')
                #question_html = urllib.unquote(question_html)
                encode_html = {}
                encode_html['content'] = json.loads(question_html, encoding = 'utf-8')
            except:
                traceback.print_exc()
                LOG.error(sys.exc_info())
                return leave_func(self, 100)

            sql_list = []
            if chapter_id:
                sql_list.append('INSERT INTO link_question_chapter(question_id, chapter_id) VALUE(%s, %s) ON DUPLICATE KEY UPDATE chapter_id = %s' % (question_id, chapter_id, chapter_id)) # 生成更新章节关联信息的SQL

            if theme: # 主题
                sql_list.append('DELETE FROM link_question_topic WHERE question_id = %s' % question_id) # 生成删除原有主题关联的SQL
                for theme_id in theme.split(','): # 将传入的主题号按逗号切割
                    if Business.is_topic(theme_id) is False: # 判断主题号是否存在
                        LOG.error('invalid theme_id[%s]' % theme_id)
                        return leave_func(self, 1)
                    sql_list.append('INSERT INTO link_question_topic (question_id, topic_id) VALUES (%s, %s)' % (question_id, theme_id)) # 生成将新主题关联插库的SQL

            question_type = Business.is_type(type_id)
            if question_type is False: # 判断题目类型是否存在
                LOG.error('invalid type_id[%s]' % type_id)
                return leave_func(self, 1)

            answer_num = 0
            if 'answer' in encode_json['content'].keys():
                if type_id == '1':
                    answer_num = len(encode_json['content']['answer'])
                elif type_id == '2':
                    answer_num = len([int(answer_group['index']) for answer_group in encode_json['content']['answer']])

            sql_list.append('UPDATE entity_question SET difficulty = %s, update_time = now(), question_type = "%s", question_group = %s, answer_num = %s WHERE id = %s' % (level_id, question_type, group_id, answer_num, question_id)) # 生成更新题目属性的SQL

            mysql_handle = Mysql().get_handle()
            mysql_cursor = mysql_handle.cursor(MySQLdb.cursors.DictCursor)
            mysql_cursor.execute('SELECT question_docx, html FROM entity_question WHERE id = %s' % question_id) # 通过题目ID查询存储的json/html文件名
            result = mysql_cursor.fetchall()
            if not result:
                LOG.error('invalid question_id[%s]' % question_id)
                return leave_func(self, 1)

            qiniu = QiniuWrap()
            mongo = Mongo()
            mongo.connect('resource')

            if result[0]['question_docx'] and '.json' in result[0]['question_docx']:
                json_name = result[0]['question_docx']
                # 将七牛上的json文件删除后重新上传
                qiniu.bucket.delete("temp", json_name)
                qiniu.upload_data("temp", json_name, question_json)
                # 将MongoDB中的json文件删除后重新上传
                mongo.select_collection('mongo_question_json')
                LOG.debug('resource.mongo_question_json.remove( { question_id: %s } )' % question_id)
                mongo.remove( { "question_id" : int(question_id) } )
                encode_json['question_id'] = int(question_id)
                LOG.debug('resource.mongo_question_json.insert_one( %s )' % encode_json)
                mongo.insert_one(encode_json)

            if result[0]['html'] and '.html' in result[0]['html']:
                html_name = result[0]['html']
                # 将七牛上的html文件删除后重新上传
                qiniu.bucket.delete("temp", html_name)
                qiniu.upload_data("temp", html_name, question_html)
                # 将MongoDB中的html文件删除后重新上传
                mongo.select_collection('mongo_question_html')
                LOG.debug('resource.mongo_question_html.remove( { question_id: %s } )' % question_id)
                mongo.remove( { "question_id" : int(question_id) } )
                encode_html['question_id'] = int(question_id)
                LOG.debug('resource.mongo_question_html.insert_one( %s )' % encode_html)
                mongo.insert_one(encode_html)

            for sql in sql_list:
                LOG.info(sql)
                mysql_cursor.execute(sql)
            mysql_handle.commit()
            mysql_cursor.close()
            mysql_handle.close()

            leave_func(self, 0)
            self.write(error_process(0))
        except Exception, e:
            LOG.error(e)
            return leave_func(self, 100)
Example #55
0
 def on_close(self):
     Control.control_clients.remove(self)
     Business.on_close(self)