如何重构代码以避免错误?

时间:2015-04-11 22:30:52

标签: python google-app-engine

我使用google appengine并使用图片上传表单字段。它已经工作多年了。最近我们开始收到错误消息。我在appengine日志中收到此错误消息

/upload_form 404 2806ms 0kb Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36 module=default version=brazil
0.1.0.30 - - [11/Apr/2015:15:25:53 -0700] "POST /upload_form HTTP/1.1" 404 84 "http://www.koolbusiness.com/ai" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36" "www.koolbusiness.com" ms=2807 cpu_ms=1970 cpm_usd=0.000009 app_engine_release=1.9.19 instance=00c61b117c883da8804d90f0539b4890fd6a4f
I 2015-04-12 00:25:50.828
user_dict | None 
E 2015-04-12 00:25:53.556
Python int too large to convert to C long

这是代码

class AdLister(BaseRequestHandler,
               blobstore_handlers.BlobstoreUploadHandler):
    csrf_protect = False

    def post(self):
        message = ''

        ad = Ad()

        if users.get_current_user():
            ad.user = users.get_current_user()

        if self.current_user is not None:
            #logging.debug('usr %s' % str(self.current_user()))
            try:
                ad.usr = self.current_user
            except Exception, e:
                logging.info('exception %s' % str(e))

        if self.request.get('type'):
            ad.type = self.request.get('type')
        if self.request.get('address'):
            ad.address = self.request.get('address')
        if self.request.get('rooms'):
            ad.number_of_rooms = int(self.request.get('rooms'))
        if self.request.get('size'):
            ad.size = float(self.request.get('size'))
        if self.request.get('regdate'):
            ad.regdate = int(self.request.get('regdate'))
        if self.request.get('mileage'):
            ad.mileage = int(self.request.get('mileage'))

        ad.category = self.request.get('category_group')

        form = AdForm(self.request.params)
        #form = AdForm(unicode(self.request.params, "utf8"))
        for city in montaomodel.City.all().fetch(9999999):  # TODO: only do this for the region

            form.area.choices.insert(city.key().id(),
                                     (str(city.key().id()), 'Select...'))

        if form.validate():
            title = to_unicode_or_bust(form.title.data)
            #unicode(form.title.data, 'utf-8')
            ad.title = title
            self.session['title'] = ad.title
            name = to_unicode_or_bust(form.name.data)  #, 'utf-8')
            ad.name = name
            self.session['name'] = ad.name
            ad.email = form.email.data
            self.session['email'] = ad.email
            ad.phoneview = form.phoneview.data
            self.session['phoneview'] = ad.phoneview
            try:
                if form.phonenumber.data:
                    ad.phonenumber = form.phonenumber.data
                    self.session['phonenumber'] = ad.phonenumber
            except:
                pass

            text = to_unicode_or_bust(form.text.data)  # , 'utf8')
            titletest = to_unicode_or_bust(form.title.data)




            ad.text = text
            self.session['text'] = ad.text
            ad.price = form.price.data.replace(' ', '').replace(',00',
                                                                '').replace('.00', '')
            try:
                if form.price.data:
                    ad.integer_price = form.price.data.replace(' ', ''
                    ).replace(',00', '').replace('.00', '')
            except:
                pass
            self.session['price'] = ad.price
            ad.url = self.request.host
            self.session['url'] = self.request.host
            ad.place = self.request.get('place')
            self.session['place'] = ad.place
            ad.postaladress = self.request.get('place')
            self.session['postaladress'] = ad.postaladress
            ad.put()
            self.session['ad_id'] = ad.key().id()
        else:

            self.render('createnewad.html', {
                'user': self.current_user,
                'session': self.auth.get_user_by_session(),
                'request': self.request,
                'form': form,
                'name': to_unicode_or_bust(form.name.data)  #.encode('utf-8')
            })
            return
        if self.request.get('currency'):
            ad.currency = self.request.get('currency')
            self.session['currency'] = ad.currency
        if self.request.get('cg'):
            ad.category = self.request.get('cg')
            self.session['category'] = ad.category
        if self.request.get('company_ad') == '1':
            ad.company_ad = True
            self.session['company_ad'] = 'True'
        ad.put()

        ad.url = self.request.host

        for upload in self.get_uploads():
            try:
                img = Image(reference=ad)
                img.primary_image = upload.key()
                image_url = images.get_serving_url(str(upload.key()), size=640)
                img.put()
                ad.hasimages = True
                ad.image_url = images.get_serving_url(str(upload.key()), size=640)
                ad.put()
                ad.blobs.append(upload.key())
                ad.put()
            except Exception, e:
                logging.error('There was an exception:%s' % str(e))
                pass
        ad.published = False
        if self.request.get('area'):
            city = \
                montaomodel.City.get_by_id(long(self.request.get('area'
                )))
            region = montaomodel.Region.get(city.region.key())
            ad.cities.append(city.key())
            ad.regions.append(region.key())
            ad.city = unicode(city.name)
            ad.region = unicode(region.name)
            ad.put()

        param = {'address': ad.city.encode('utf-8'), 'sensor': 'false'}
        encoded_param = urllib.urlencode(param)
        url = 'http://maps.googleapis.com/maps/api/geocode/json'
        url = url + '?' + encoded_param
        result = urlfetch.fetch(url)
        jsondata = json.loads(result.content)

        try:
            latlng = jsondata['results'][0]['geometry']['location']
            lat = latlng['lat']
            lon = latlng['lng']
            ad.geopt = db.GeoPt(lat, lon)
        except Exception, e:
            pass
        ad.put()
        if self.current_user:
            ad.userID = str(self.current_user.auth_ids[0])
            ad.put()
            ad.usr = self.current_user.key.to_old_key()
            ad.put()

        image = ad.matched_images.get()
        image_url = None
        if image:
            if image.primary_image:
                try:
                    image_url = \
                        images.get_serving_url(str(image.primary_image.key()),
                                               size=640)
                except Exception, e:
                    image_url = '/images/' + str(image.key().id()) \
                                + '_small.jpg'
            else:
                image_url = '/images/' + str(image.key().id()) \
                            + '_small.jpg'
        imv = []
        for i in ad.matched_images:
            if i.primary_image:
                try:
                    i1 = \
                        images.get_serving_url(str(i.primary_image.key()))
                    imv.append(i1)
                except Exception, e:
                    i1 = '/images/' + str(image.key().id()) \
                         + '_small.jpg'
                    imv.append(i1)

        if ad.price:  # and doesn't contain separators
            try:
                price = \
                    i18n.I18n(self.request).format_decimal(int(ad.price))
            except Exception, e:
                price = ad.price
        else:
            price = ad.price

        self.render('preview.html', {
            'user': self.current_user,
            'session': self.auth.get_user_by_session(),
            'request': self.request,
            'ad': ad,
            'image_url': image_url,
            'imv': imv,
            'len': len(imv),
            'form': PreviewAdForm(),
            'price': price,
            })

更新

违规代码就是这一行

form.area.choices.insert(long(city.key().id()), (str(city.key().id()), 'Select...'))

它的ID太大了。我把声明放在try ...块中,所以它暂时传递错误。我想做一个重构,所以它不能获取所有城市,只能获取该地区的城市。

0 个答案:

没有答案