Beispiel #1
0
def create():
    """
    Creates an ad
    
    Requires the following param:
        * long, lat
        * category(id) , email, title, price, image, description
    """
    # validation
    required_fields = ("long", "lat", "email", "title", "price", "image")
    for field in required_fields:
        if not field in request.form:
            return jsonify({"res": False, "error": "There is an error creating your ad due to missing field(s)."})

    # check for price integer
    try:
        float(request.form.get("price"))
    except ValueError:
        return jsonify({"res": False, "error": "Price needs to be a numerical value."})

    # email format validation
    validate_me = StringValidator(request.form.get("email"))
    if not validate_me.isEmail():
        return jsonify({"res": False, "error": "Not a valid email address."})

    from db import Location, Category, Ad

    location = Location(longitude=request.form.get("long"), latitude=request.form.get("lat"))
    category = Category.get(request.form.get("category"))
    id = Ad.create(
        location,
        request.form.get("email"),
        request.form.get("title"),
        request.form.get("price"),
        save_file(request.form.get("image")),
        category,
        request.form.get("description", ""),
    )
    return jsonify({"res": id})
    def get_ads_and_write_to_db(self, link, response):

        try:
            category = Category.get(name=link)

        except DoesNotExist:
            category = Category.create(
                name=link
            )

        ad_blocks = response.html.xpath('//div[@class="offer-wrapper"]')
        for ad in ad_blocks:
            try:
                ad_title = ad.xpath('//h3')[0].text
                ad_date = ad.xpath('//p[@class="lheight16"]/small[2]')[0].text
                ad_price = ad.xpath('//p[@class="price"]')[0].text
                ad_photo = ad.xpath('//img/@src')[0]
                ad_link = ad.xpath('//h3/a/@href')[0]
                ad_city = ad.xpath('//p[@class="lheight16"]/small[1]')[0].text

                ad_data = {
                    'title': ad_title,
                    'date': ad_date,
                    'price': ad_price,
                    'photo': ad_photo,
                    'link': ad_link,
                    'city': ad_city,
                    'category_id': category
                }

            except Exception as e:
                print('Parse error\n', e, type(e))

            try:
                Ad.create(**ad_data)
            except Exception as e:
                print('DB error\n', e, type(e))
Beispiel #3
0
from db import Ad, Category, Author

cat = Category.get(Category.id == 4)

for ad in cat.ads:
    print(ad.name, ad.price)