Example #1
0
def put_new_city():
    session = get_session()
    content = g.data

    locale = get_post_locale(session)

    city = City()
    name_id = str(uuid4())
    locale_string = LocaleString(id=name_id,
                                 locale=locale,
                                 text=content['name'])
    city.name_id = name_id
    city.name.set(locale_string)

    description_id = str(uuid4())
    locale_string = LocaleString(id=description_id,
                                 locale=locale,
                                 text=content['description'])
    city.description_id = name_id
    city.description.set(locale_string)

    city.image_link = content['image_link']

    session.add(city)

    session.commit()
    session.close()

    return 'ok'
Example #2
0
 def __generateBrief(self, o):
     res = {}
     tender = o.Tender
     city = o.City
     res.update(Tender.generateBrief(tender=tender))
     res.update(City.generate(city=city))
     return res
Example #3
0
def show(city_id):
    schema = CitySchema()
    city = City.get(id=city_id)

    if not city:
        abort(404)

    return schema.dumps(city)
Example #4
0
def delete(city_id):
    city = City.get(id=city_id)

    if not city:
        abort(404)

    city.delete()
    db.commit()

    return '', 204
Example #5
0
def create():
    schema = CitySchema()
    try:
        data = schema.load(request.get_json())
        city = City(**data)
        db.commit()
    except ValidationError as err:
        return jsonify({
            'message': 'Validation failed',
            'errors': err.messages
        }), 422

    return schema.dumps(city), 201
Example #6
0
 def save(city_id, desc, temp_max, temp_min, pressure, humidity, visibility,
          wind_speed, dt):
     city = City.get_by_id(city_id)
     entry = Weather(city=city,
                     description=desc,
                     temp_max=temp_max,
                     temp_min=temp_min,
                     pressure=pressure,
                     humidity=humidity,
                     visibility=visibility,
                     wind_speed=wind_speed,
                     month=utils.get_month_by_dt(dt),
                     dt=dt)
     return entry
Example #7
0
def update(city_id):
    schema = CitySchema()
    city = City.get(id=city_id)

    if not city:
        abort(404)

    try:
        data = schema.load(request.get_json())
        city.set(**data)
        db.commit()
    except ValidationError as err:
        return jsonify({
            'message': 'Validation failed',
            'errors': err.messages
        }), 422

    return schema.dumps(city)
Example #8
0
    def __generateTender(self, t):
        tender = t.Tender
        city = t.City

        res = {}
        res.update(Tender.generate(tender=tender))
        res.update(City.generate(city=city))
        # # 列表中不带详情
        # if tag is not None:
        #     del res['detail']
        # else:
        #     # 详情中的情况
        #     favorite = t.Favorite
        #     if favorite is not None:
        #         res['favorite'] = True
        #     else:
        #         res['favorite'] = False
        return res
Example #9
0
 def post(self):
    """
    Parses a list of police/fire calls and fires off a task for each one
    """
    incidentType = None
    incidentTypeNames = [incident.name.lower() for incident in IncidentType.all()]
    
    city = None
    cityNames = [city.name.lower() for city in City.all()]
    
    lines = self.request.get('report').split('\n')
    lineNum = 0
    
    startDate = None
    endDate = None
    
    for strippedLine in [line.strip() for line in lines if line.strip() != '']:
       try:
          if 0 == lineNum:
             startDate = strippedLine
          elif 1 == lineNum:
             endDate = strippedLine
          else:
             if strippedLine.lower() in incidentTypeNames:
                incidentType = IncidentType.all().filter('name =', strippedLine.lower()).get()
                city = None
             elif strippedLine.lower() in cityNames:
                city = City.all().filter('name =', strippedLine.lower()).get()
             else:
                match = re.search('^[0-9]+', strippedLine)
                lineItemTokens = strippedLine.split(',')
                if None != match and 3 == len(lineItemTokens):
                   timeToken = lineItemTokens[0]
                   descToken = lineItemTokens[1].title()
                   addressToken = lineItemTokens[2].title()
                   
                   # Check for date, anything on or after 3 pm is the start date
                   # anything on or after 12 am is the end date
                   dateString = endDate
                   if int(match.group(0)) >= 3 and int(match.group(0)) < 12 and -1 != timeToken.find('p.m.'):
                      dateString = startDate
                      
                   # Now make sure lines such as 3 p.m = 3:00 p.m.
                   if (-1 == timeToken.find(':')):
                      timeToken = timeToken.replace(' ', ':00 ')
                   
                   # Now replace AM or PM with a.m or p.m.
                   dateOfIncident = datetime.strptime(
                    '%s %s' %(dateString, timeToken.replace('a.m.', 'AM').replace('p.m.', 'PM')), 
                    '%m/%d/%Y %I:%M %p')
                                                                         
                   # We've parsed out all informaton so create a record...just bail on this record
                   # if we're in a bad state
                   assert(None != incidentType and None != city)
                   incidentReport = IncidentReport(
                    incidentType = incidentType,
                    description = descToken,
                    time = dateOfIncident,
                    city = city,
                    address = addressToken)
                   incidentReport.save()
                   
                   # Add background task for getting geo coordinates of the address
                   taskqueue.add(url='/retrieve-incident-latlong', params={'id': incidentReport.key().id()})
                #
                else:
                   incidentType = None
                   city = None
                   raise Exception('Unrecognized line')
                #
             #
          #
       #  
       except (Exception, AssertionError) as e:
          if isinstance(e, AssertionError):
             e = 'Incident type or city was null.'
          self.response.out.write("Error processing line: %s <br />" %(strippedLine))
          self.response.out.write('<div style="margin:5px;">%s</div>' %(str(e)))
          self.response.out.write('<br />')
       #
       lineNum += 1
   def get(self):
      """
      Create default data
      """
      city = City(name='la crosse')
      city.save()
      self.response.out.write('Created la crosse<br/>')

      city = City(name='onalaska')
      city.save()
      self.response.out.write('Created onalaska<br/>')

      city = City(name='holmen')
      city.save()
      self.response.out.write('Created holmen<br/>')

      city = City(name='west salem')
      city.save()
      self.response.out.write('Created west salem<br/>')

      city = City(name='bangor')
      city.save()
      self.response.out.write('Created bangor<br/>')

      city = City(name='town of campbell')
      city.save()
      self.response.out.write('Created town of campbell<br/>')
      
      city = City(name='town of shelby')
      city.save()
      self.response.out.write('Created town of shelby<br/>')
      
      city = City(name='rockland')
      city.save()
      self.response.out.write('Created rockland<br/>')

      city = City(name='melrose')
      city.save()
      self.response.out.write('Created melrose<br/>')
      
      city = City(name='mindoro')
      city.save()
      self.response.out.write('Created mindoro<br/>')
      
      city = City(name='cashton')
      city.save()
      self.response.out.write('Created cashton<br/>')
      
      city = City(name='coon valley')
      city.save()
      self.response.out.write('Created coon valley')

      city = City(name='trempealeau')
      city.save()
      self.response.out.write('Created trempealeau')
      
      
      aType = IncidentType(name="police calls")
      aType.save()
      self.response.out.write('Created police calls type<br/>')

      aType = IncidentType(name="fire calls")
      aType.save()
      self.response.out.write('Created fire calls type<br/>')
Example #11
0
db.generate()


def request_weather(city):
    apiClienet = ApiClient(CONFIG['appid'], city.city_id)
    response = apiClienet.weather()
    response = json.loads(response.text)

    # Save weather to DB if entry for this time does not exist
    if len(Weather.get_by_unix(response['dt'])) == 0:
        weather_entry = Weather.save(city_id=city.city_id,
                                     desc=response['weather'][0]['main'],
                                     temp_max=response['main']['temp_max'],
                                     temp_min=response['main']['temp_min'],
                                     pressure=response['main']['pressure'],
                                     humidity=response['main']['humidity'],
                                     visibility=response['visibility'],
                                     wind_speed=response['wind']['speed'],
                                     dt=response['dt'])
        print("Entry for time {} added successfully".format(
            unix_to_datetime(weather_entry.dt)))
        return weather_entry
    print("Entry was not added, because it already exists for time {}".format(
        unix_to_datetime(response['dt'])))
    return None


if __name__ == '__main__':
    city = City.get_by_name('Stockholm')
    request_weather(city)
Example #12
0
def parse_city_callback(line):
    city = City(line)
    cities.append(city.to_dict())
    save_extra_city_fields(city)
Example #13
0
 def __generateBiddingDetail(self, b):
     res = {}
     res.update(WinBiddingPub.generate(b=b.WinBiddingPub))
     res.update(City.generate(city=b.City))
     return res
Example #14
0
 def __generateTender(self, t):
     res = {}
     res.update(Tender.generateBrief(tender=t.Tender))
     res.update(City.generate(city=t.City))
     return res
Example #15
0
 def __generateBidding(self, b):
     res = {}
     res.update(WinBiddingPub.generateBrief(result=b.WinBiddingPub))
     res.update(City.generate(city=b.City))
     return res
Example #16
0
 def __generateCity(self, c):
     res = {}
     res.update(City.generate(city=c))
     return res
Example #17
0
def index():

    schema = CitySchema(many=True)
    cities = City.select()
    return schema.dumps(cities)