def test_is_hogemail(session):
    # Add user
    user1 = User(name='name_1', fullname='fullname_1', nickname='nickname_1')
    user2 = User(name='name_2', fullname='fullname_2', nickname='nickname_2')
    user3 = User(name='name_3', fullname='fullname_3', nickname='nickname_3')

    for user in [user1, user2, user3]:
        session.add(user)

    # Add address
    address1 = Address(email_address='*****@*****.**',
                       user_id=user1.user_id,
                       user=user1)
    address2 = Address(email_address='*****@*****.**',
                       user_id=user2.user_id,
                       user=user2)
    address3 = Address(email_address='address_3@hogemailcom',
                       user_id=user3.user_id,
                       user=user3)

    for address in [address1, address2, address3]:
        session.add(address)

    # Execute test
    result = is_hogemails(session)
    assert not result
示例#2
0
def _parse_wrapping_event(ts: str, fields: dict[str, str]) -> WrappingEvent:
    sender: Address = Address(fields["sender (NineChronicles)"])
    recipient: Address = Address(fields["recipient (Ethereum)"])
    amount: float = float(fields["amount"])
    fee: float = float(fields["fee"])

    nc_tx = fields["9c network transaction"].replace("<", "").replace(">", "")
    eth_tx = fields["Ethereum network transaction"].replace("<", "").replace(">", "")

    refund_txid: Optional[TxId] = _map(fields.get("refund transaction"), lambda x: TxId(urllib3.util.url.parse_url(x.replace("<", "").replace(">", "")).query))
    refund_amount = _map(fields.get("refund amount"), float)

    nc_txid: TxId = TxId(urllib3.util.url.parse_url(nc_tx).query)

    network_type = NetworkType(urllib3.util.url.parse_url(nc_tx).path.split("/")[1])
    eth_txid = TxId(urllib3.util.url.parse_url(eth_tx).path.split("/")[-1])

    return WrappingEvent(
        network_type,
        ts,
        sender,
        recipient,
        amount,
        fee,
        nc_txid,
        eth_txid,
        refund_txid,
        refund_amount,
    )
示例#3
0
def save_order_addresses(id):
    user_authenticated_id = get_jwt_identity()

    pickup_address = Address(address=request.json.get('pickup').get('address'),
                             city=request.json.get('pickup').get('city'),
                             country=request.json.get('pickup').get('country'),
                             cp=request.json.get('pickup').get('CP'),
                             user_id=user_authenticated_id)
    pickup_address.save()

    delivery_address = Address(
        address=request.json.get('delivery').get('address'),
        city=request.json.get('delivery').get('city'),
        country=request.json.get('delivery').get('country'),
        cp=request.json.get('delivery').get('CP'),
        user_id=user_authenticated_id)
    delivery_address.save()

    order = Order.query.get(id)

    order.address_delivery = delivery_address
    order.address_pickup = pickup_address

    order.save()

    DBManager.commitSession()
    order_new_data_mail(order)

    return jsonify(order.serializeForEditView()), 200
    def setUp(self):
        """Create test client, add sample data."""

        db.drop_all()
        db.create_all()

        self.client = app.test_client()

        # add states
        s1 = State(name="oh")
        s2 = State(name="ca")
        s3 = State(name="ny")
        s4 = State(name="nc")
        db.session.add_all([s1, s2, s3, s4])
        db.session.commit()

        # add test users
        self.testuser = User.signUp(username="******",
                                    password="******",
                                    email="*****@*****.**",
                                    address_line1="123 Sunset Ave",
                                    address_line2="Apt B",
                                    state_name="ca",
                                    zip_code="99999")
        db.session.commit()

        self.testuser = User.query.get(self.testuser.id)

        self.testuser_id = 111
        self.testuser.id = self.testuser_id
        db.session.commit()

        a1 = Address(user_id=self.testuser_id,
                     address_line1="123 Street",
                     state_name="ri",
                     zip_code="43015",
                     favorite=True,
                     nickname="Brutus's House")
        a3 = Address(user_id=self.testuser_id,
                     address_line1="789 Street",
                     state_name="ny",
                     zip_code="88888",
                     favorite=False,
                     nickname="Sister's House")
        a4 = Address(user_id=self.testuser_id,
                     address_line1="112 Street",
                     state_name="nc",
                     zip_code="88888",
                     favorite=True,
                     nickname="Vacation Home")
        db.session.add_all([a1, a3, a4])
        db.session.commit()

        ua1 = User_Addresses(user_id=self.testuser_id, address_id=4)
        ua2 = User_Addresses(user_id=self.testuser_id, address_id=5)
        ua3 = User_Addresses(user_id=self.testuser_id, address_id=6)

        db.session.add_all([ua1, ua2, ua3])
        db.session.commit()
 def test_create_user_and_addr2(self):
     user = User(id=3, name="Alice", fullname="Alice Brown")
     user.addresses = [
         Address(id=4, email_address="*****@*****.**"),
         Address(id=5, email_address="*****@*****.**")
     ]
     session.add(user)
     session.commit()
示例#6
0
def newRestaurant():
    '''
    {
    "name" : "Drums",
    "category" : "Italian",
    "street" : "254 PLX St.",
    "city" : "Arlington",
    "state" : "TX",
    "zipcode" : 75043

    }
    '''

    restaurantName = request.get_json()["name"]
    categoryName = request.get_json()["category"]

    street = request.get_json()["street"]
    city = request.get_json()["city"]
    state = request.get_json()["state"]
    zipcode = request.get_json()["zipcode"]

    try:
        restaurant_exists = session.query(Restaurant).filter(
            Restaurant.restaurant_name == restaurantName).scalar() is not None
        address_exists = session.query(Address).filter(
            Address.address == street, Address.city == city,
            Address.state == state,
            Address.zipcode == zipcode).scalar() is not None

    except ValueError:
        return ("Unexpected error:", sys.exc_info()[0])

    if restaurant_exists:
        if address_exists:
            return 'Restaurant Already Exists'
        else:
            newAddress = Address(address=street,
                                 city=city,
                                 state=state,
                                 zipcode=zipcode,
                                 restaurant_name=restaurantName)
            session.add(newAddress)
            session.commit()
            return "New Retaurant added"
    else:
        newRestaurant = Restaurant(restaurant_name=restaurantName,
                                   restaurant_category=categoryName)
        newAddress = Address(address=street,
                             city=city,
                             state=state,
                             zipcode=zipcode,
                             restaurant_name=newRestaurant.restaurant_name)

        session.add(newRestaurant)
        session.add(newAddress)
        session.commit()
        return "New Retaurant added"
示例#7
0
def _parse_unwrapping_failure_event(ts: str, fields: dict[str, str]) -> UnwrappingFailureEvent:
    sender: Address = Address(fields["sender (Ethereum)"])
    recipient: Address = Address(fields["recipient (NineChronicles)"])
    amount: float = float(fields["amount"])

    eth_tx = fields["Ethereum transaction"].replace("<", "").replace(">", "")
    eth_txid = TxId(urllib3.util.url.parse_url(eth_tx).path.split("/")[-1])

    return UnwrappingFailureEvent(
        ts,
        sender,
        recipient,
        amount,
        eth_txid,
    )
示例#8
0
def add_user():
    if len(request.form['fname']) < 2:
        flash("First name is required")
    if len(request.form['lname']) < 2:
        flash("Last name is required")
    if not EMAIL_REGEX.match(request.form['email']):
        flash("Valid email is required")
    if len(request.form['address']) < 2:
        flash("Address is required")
    if len(request.form['city']) < 2:
        flash("City must be at least 2 characters")
    if len(request.form['state']) < 2:
        flash("State initials required, 2 characters")
    if len(request.form['password']) < 5:
        flash("password isn't long enough")
    if request.form['password'] != request.form['cpassword']:
        flash("password dont match")
    if '_flashes' not in session:
        new_user = User(first_name=request.form['fname'],
                        last_name=request.form['lname'],
                        email=request.form['email'],
                        password_hash=bcrypt.generate_password_hash(
                            request.form['password']))
        db.session.add(new_user)
        db.session.commit()
        flash("Successfully added user")
        new_address = Address(user_id=new_user.id,
                              address=request.form['address'],
                              city=request.form['city'],
                              state=request.form['state'])
        db.session.add(new_address)
        db.session.commit()
        flash("Address added")
        return redirect("/")
    return redirect('/')
示例#9
0
def register():
    form = RegisterForm()
    if request.method == "POST" and form.validate_on_submit():
        #Verificando que el usuario aun no se haya registrado
        user = User.query.filter_by(email=form.email.data).first()
        if (user):
            flash(_("The email %(email)s is already in use"),
                  email=form.email.data)
            return redirect(url_for('auth.register'))

        address = Address(city=form.city.data,
                          state=form.state.data,
                          municipality=form.municipality.data,
                          street=form.street.data,
                          postal_code=form.postal_code.data,
                          interior_number=form.interior_number.data,
                          exterior_number=form.exterior_number.data)
        user = User(first_name=form.first_name.data,
                    last_name=form.last_name.data,
                    email=form.email.data,
                    addresses=[address])
        user.set_password(form.password.data)
        user.set_user_secret(form.email.data)
        db.session.add(user)
        db.session.commit()
        send_registration_email(user)
        flash(
            _("Congratulations you are a registered user, please confirm your email %(email)s!",
              email=form.email.data))

        return redirect(url_for('auth.login'))

    return render_template('auth/register.html', form=form)
示例#10
0
    def test_attach_an_address(self):
        a = Address()
        u = User()

        u.addresses.append(a)

        self.assertEqual(len(u.addresses), 1)
示例#11
0
def addaddress():
    #返回参数结构
    responseData = {"status": 0, "message": '', "result": {}}
    if request.method == "POST":
        ContactPerson = request.form.get("ContactPerson")
        ContactNumber = request.form.get("ContactNumber")
        ContactAddress = request.form.get("ContactAddress")
        ContactDetailAddress = request.form.get("ContactDetailAddress")
        isDefault = request.form.get("isDefault")
        AddressId = str(uuid.uuid1())
        if not all([
                ContactPerson, ContactNumber, ContactAddress,
                ContactDetailAddress
        ]):
            responseData["status"] = 1
            responseData["message"] = "缺少必要的业务参数!"
        else:
            address = Address(AddressId=AddressId,
                              ContactPerson=ContactPerson,
                              ContactNumber=ContactNumber,
                              ContactAddress=ContactAddress,
                              ContactDetailAddress=ContactDetailAddress,
                              isDefault=isDefault)
            db.session.add(address)
            db.session.commit()
            responseData["status"] = 0
            responseData["message"] = "添加地址成功!"

    # 返回数据
    return jsonify(responseData)
示例#12
0
def add_care_home():
    form = CareHomeForm(request.form)

    if request.method == 'POST':
        operator = Operator(name=form.operator_name.data,
                            phone=form.phone.data,
                            certification=form.certification.data,
                            license_expiration=form.license_expiration.data)
        address = Address(street=form.address_street.data,
                          city=form.address_city.data,
                          region=form.address_region.data,
                          state='HI',
                          zip=form.address_zip.data,
                          email=form.email.data,
                          operator=operator)
        carehome = CareHome(
            name=form.carehome_name.data,
            type=form.type.data,
            open_rooms=form.open_rooms.data,
            max_rooms=form.private_rooms.data + form.shared_rooms.data,
            patient_gender=form.patient_gender.data,
            patient_max_age=form.patient_age.data,
            private_patients=form.patient_private.data,
            medicaid_patients=form.patient_medicaid.data,
            ssi_patients=form.patient_ssi.data,
            assistive_walking_devices=str(
                form.patient_walking_device.data).replace('[', '').replace(
                    ']', '').replace('\'', ''),
            behavioral_issues_patient=form.patient_behavioral.data,
            dialysis_patient=form.patient_dialysis.data,
            hospice_patient=form.patient_hospice.data,
            insulin_patient=form.patient_insulin.data,
            tube_feed_patient=form.patient_tube_feed.data,
            wounded_patient=form.patient_wounds.data,
            max_weight_patient=form.patient_weight.data,
            case_management_company=form.case_management_company.data,
            previous_experience=form.previous_experience.data,
            subs=form.subs.data,
            open_year=form.carehome_open_year.data,
            notes=form.notes.data,
            operator=operator)
        private_rooms = Room(min_price=form.min_price_private.data,
                             max_price=form.max_price_private.data,
                             amount=form.private_rooms.data,
                             type=Room.Type.PRIVATE,
                             carehome=carehome)
        shared_rooms = Room(min_price=form.min_price_shared.data,
                            max_price=form.max_price_shared.data,
                            amount=form.shared_rooms.data,
                            type=Room.Type.SHARED,
                            carehome=carehome)
        db.session.add(operator)
        db.session.add(address)
        db.session.add(carehome)
        db.session.add(private_rooms)
        db.session.add(shared_rooms)
        db.session.commit()
        flash('Care Home added', 'success')
        return redirect(url_for('care_homes'))
    return render_template('addcarehome.html', form=form)
示例#13
0
def update_address():
    """ Update the user's address"""
    session = connect()
    try:
        user = load_user(current_user.id)
        address = get_address(user.address_id)
    except AttributeError:
        return 'Error getting user data'
    if address is None:
        address = Address()
    if request.method == 'POST':
        if request.form['street_1']:
            address.street_1 = request.form['street_1']
        if request.form['street_2']:
            address.street_2 = request.form['street_2']
        if request.form['city']:
            address.city = request.form['city']
        if request.form['state']:
            address.state = request.form['state']
        if request.form['zip_code']:
            address.zip_code = request.form['zip_code']
        address_string = get_address_string(address)
        if validate_address(address_string) is False:
            flash("Address is invalid or outside delivery radius!")
            return redirect(url_for('cart_edit_address'))
        address = session.add(address)
        user.address_id = get_address_id(address)
        user = session.merge(user)
        flash("Address saved!")
        session.commit()
    return redirect(url_for('show_cart'))
示例#14
0
def myaddress(user_id):
    address_check = Address.query.filter_by(user_id=current_user.id).first()
    if request.method == "POST":
        town = request.form.get('town')
        street = request.form.get('street')
        delivery = request.form.get('delivery')
        postal_code = request.form.get('postal_code')

        if not address_check:
            address = Address(town=town,
                              street=street,
                              delivery=delivery,
                              postal_code=postal_code,
                              user_id=user_id)
            db.session.add(address)
        else:
            address_check.town = town
            address_check.street = street
            address_check.delivery = delivery
            address_check.postal_code = postal_code

        db.session.commit()

        return redirect(url_for('home'))

    return render_template(
        "address.html",
        address=Address.query.filter_by(user_id=current_user.id).first())
示例#15
0
def _parse_refund_event_slack_response(message: SlackResponse) -> Optional[RefundEvent]:
    if "attachments" not in message:
        return None

    attachment: dict = message["attachments"][0]

    if "fields" not in attachment:
        return None

    fields = dict(map(lambda x: (x["title"], x["value"]), attachment["fields"]))
    print(fields)

    address: Address = Address(fields["Address"])
    reason: str = fields["Reason"]
    request_txid = urllib3.util.url.parse_url(fields["Request transaction"].replace("<", "").replace(">", "")).query
    refund_txid = urllib3.util.url.parse_url(fields["Refund transaction"].replace("<", "").replace(">", "")).query
    request_amount = float(fields["Request Amount"])
    refund_amount = float(fields["Refund Amount"])
    return RefundEvent(
        request_amount=request_amount,
        request_txid=request_txid,
        address=address,
        reason=reason,
        refund_txid=refund_txid,
        refund_amount=refund_amount,
        ts=message["ts"],
        network_type=NetworkType.MAINNET
    )
示例#16
0
def update_address_details(request, address_id):

    if request.method == 'PUT':

        try:

            payload = json.loads(request.body)

            user_id = payload['user_id']
            town = payload['town']
            estate = payload['estate']
            street_number = payload['street_number']
            status = payload['status']
            stayed_from = payload['stayed_from']

            address_data = Address(user_id=user_id,
                                   town=town,
                                   estate=estate,
                                   street_number=street_number,
                                   status=status,
                                   stayed_from=stayed_from)

            response = address_data.update_address_data(address_id)

        except:
            response = json.dumps([{'message': 'invalid request'}])

    return HttpResponse(response, content_type='text/json')
示例#17
0
def add_address():
    if request.method == "GET":
        return render_template('add_address.html')
    else:
        id = request.values.get('id')
        username = request.values.get('username')
        phone = request.values.get('phone')
        address = request.values.get('address')
        is_address = request.values.get('is_address')
        status = request.values.get('status')
        has_address = Address.query.filter(Address.phone == phone,
                                           Address.address == address).first()
        if has_address:
            return json.dumps({'code': 201, 'message': "该地址已存在,请重新添加"})
        else:
            address_add = Address(phone=phone,
                                  username=username,
                                  is_address=is_address,
                                  status=status,
                                  address=address)
            if (is_address == 1 and status == 1):
                User.query.filter_by(id=id).update({'address': address})
                db.session.add(address_add)
                db.session.commit()
                return json.dumps({'code': 200, 'message': "新增成功"})
            else:
                db.session.add(address_add)
                db.session.commit()
                return json.dumps({'code': 200, 'message': "新增成功"})
def address_from_paypal_transaction(
        raw_transaction: dict) -> Union[Address, None]:

    country = None
    city = None
    state = None
    postal_code = None
    street = None

    try:
        address = raw_transaction["shipping_info"]["address"]
        city = address["city"]
        state = address["state"]
        postal_code = address["postal_code"]
        country = address["country_code"]
    except KeyError as error:
        transaction_id = raw_transaction["transaction_info"]["transaction_id"]
        logger.debug("Complete address not found in PayPal transaction %s: %s",
                     transaction_id, error)
        return None
    else:
        if "line2" in address and address["line2"]:
            street = address["line1"] + ", " + address["line2"]
        else:
            street = address["line1"]

    address = Address(mailing_country=country,
                      mailing_city=city,
                      mailing_state=state,
                      mailing_postal_code=postal_code,
                      mailing_street=street)
    return address
示例#19
0
async def main():
    file_list = cj.ADD_FEE_LIST.keys()
    futures = [
        asyncio.ensure_future(
            parse_zipcode(
                '{path}/{f_name}.txt'.format(path=path.DATA_PATH,
                                             f_name=f_name),
                cj.ADD_FEE_LIST[f_name])) for f_name in file_list
    ]

    futures.extend([
        asyncio.ensure_future(
            parse_jeonnam_zipcode(
                '{path}/전라남도.txt'.format(path=path.DATA_PATH),
                cj.ADD_FEE_JEONAM)),
        asyncio.ensure_future(
            parse_incheon_zipcode(
                '{path}/인천광역시.txt'.format(path=path.DATA_PATH),
                cj.ADD_FEE_INCHEON)),
        asyncio.ensure_future(
            parse_jeju_zipcode(
                '{path}/제주특별자치도.txt'.format(path=path.DATA_PATH)))
    ])

    results = await asyncio.gather(*futures)
    for result in results:
        session.bulk_save_objects([Address(**item) for item in result])
        session.commit()
示例#20
0
def add_address_from_url(address_url, session=None):
    if not address_url.startswith('/off/'):
        address_url = '/off/' + address_url
    if not address_url.endswith('.html'):
        address_url += '.html'

    stored_address = session.query(Address).filter(Address.url == address_url).one_or_none()
    if stored_address is not None:
        return stored_address.id

    try:
        print(address_url)
        r = requests.get('http://www.vl.ru' + address_url)
        if r.status_code == 200:
            addr = title_re.search(r.text)
            if addr:
                addresses = geocoder.city_filter(geocoder.request(q=addr.group(1)))
                if len(addresses) > 1:
                    return None

                address = geocoder.extract_streetname(addresses[0])
                a = Address(address=address, url=address_url)
                session.add(a)
                session.commit()
                session.flush()
                return a.id
    except Exception as e:
        traceback.print_exc()
    return None
示例#21
0
文件: db.py 项目: Techzune/SWA_Assn3
def get_user_purchases(user, db=None):
    """
    Gets all purchases by user.

    :param user: User, the user to find purchases for
    :param db: optional, the database connection
    """
    db = db or get_db()
    cur = db.cursor()

    # insert the purchase
    cur.execute("""
        SELECT PurchaseID, TotalPrice, CreditCard, Address
        FROM Purchase
        WHERE Username=? 
    """, [user.username])

    purchases = []
    for row1 in cur.fetchall():
        purchase = Purchase(username=user.username, id_=row1[0], total_price=row1[1],
                            credit_card=row1[2], address=Address().from_str(row1[3]))
        cur.execute("""
            SELECT InventoryItemID, Price, Quantity
            FROM PurchaseItem
            WHERE PurchaseID=?
        """, [purchase.id_])
        for row2 in cur.fetchall():
            item = get_inventory_item(InventoryItem(row2[0]), db)
            purchase.items.append(ShoppingCartItem(item=item, price=row2[1], qty=row2[2]))
        purchases.append(purchase)

    cur.close()
    return purchases
示例#22
0
def map_json_to_address(data: dict) -> Address:
    user_id = data.get('userId', None)
    street = data.get('street', None)
    street2 = data.get('street2', None)
    city = data.get('city', None)
    state = data.get('state', None)
    zip_code = data.get('zipCode')

    return Address(user_id, street, street2, city, state, zip_code)
示例#23
0
def construct_version_msg():
    version = MY_VERSION
    services = 1024 + 8 + 4 + 2 + 1  # turn 'em all on
    timestamp = math.floor(datetime.datetime.utcnow().timestamp())
    addr_recv = Address(services=services, ip=0, port=0, time=None)
    addr_from = Address(services=services, ip=0, port=0, time=None)
    nonce = make_nonce(8)
    user_agent = USER_AGENT
    # FIXME
    start_height = 1
    relay = 1
    v = Version(version, services, timestamp, addr_recv, addr_from, nonce,
                user_agent, start_height, relay)

    command = encode_command(b'version')
    payload = v.serialize()
    msg = Message(command, payload)
    return msg
示例#24
0
文件: views.py 项目: Chalebgwa/EPR
def patient_all():
    if request.method == "GET":
        records = Patient.select()
        return template("index.html", items=records)

    elif request.method == "POST":
        json = request.POST

        # check to see if request has provided all necessary values to create object
        #

        name = json["pname"]
        surname = json["surname"]
        dob = json["dob"]
        gp = GP[app.config["user_id"]]
        status = True
        city = json["city"]
        district = json["district"]

        address = Address(cityName=city,
                          districtName=district,
                          districtCode="fix this")

        patient = Patient(name=name,
                          sex="fix this",
                          dob=dob,
                          address=address,
                          gp=gp,
                          status=status)
        #save progress
        db.commit()

        #redirect to the newly created patient's page
        redirect("/patient/{}".format(patient.id))

    elif request.method == "DELETE":

        patient_id = request.POST.id.strip()
        try:
            patient = Patient[patient_id]
        except:
            return "Patient does not exist"
        patient.delete()

    elif request.method == "PUT":
        json = request.POST
        update = json["update"]
        value = json["value"]
        id = json["id"]
        with db_session():
            try:
                patient = Patient[id]
            except:
                return {"message": 'patient not found'}
            setattr(patient, update, value)
            return {"message": "patient updated"}
    return {"message": "missing token"}
 def test_create_user_and_addr(self):
     """
     手工的方式,没有利用SA的relationship
     """
     user = User(id=3, name="Alice", fullname="Alice Brown")
     addr = Address(id=4, email_address="*****@*****.**", user_id=3)
     session.add(user)
     session.add(addr)
     session.commit()
示例#26
0
def _parse_wrapping_failure_event(ts: str, fields: dict[str, str]) -> WrappingFailureEvent:
    sender: Address = Address(fields["sender (NineChronicles)"])
    recipient: Address = Address(fields["recipient (Ethereum)"])
    amount: float = float(fields["amount"])

    nc_tx = fields["9c network transaction"].replace("<", "").replace(">", "")
    nc_txid: TxId = TxId(urllib3.util.url.parse_url(nc_tx).query)

    network_type = NetworkType(urllib3.util.url.parse_url(nc_tx).path.split("/")[1])

    return WrappingFailureEvent(
        network_type,
        ts,
        sender,
        recipient,
        amount,
        nc_txid,
    )
示例#27
0
def create_address_query(city_id, street, cep, number, neighborhood):
    new_address = Address(street=street,
                          cep=cep,
                          number=number,
                          neighborhood=neighborhood,
                          city_id=city_id)
    db.session.add(new_address)
    db.session.flush()
    db.session.commit()
    return new_address.id
示例#28
0
def create_address():
    address = Address()
    address_hash = getHash(address)
    address.number = "%s" % address_hash
    address.street = "street %s" % address_hash
    address.neighbourhood = "neighbourhood %s" % address_hash
    address.city = "city %s" % address_hash
    address.federal_state = "federal_state %s" % address_hash
    address.cep = "cep %s" % address_hash
    address.country = "country %s" % address_hash
    return address
示例#29
0
    def create_inst_stub(invite):
        """Create a stub of institution."""
        institution_stub = Institution()
        institution_stub.name = invite.suggestion_institution_name
        institution_stub.email = invite.invitee
        institution_stub.state = 'pending'
        institution_stub.address = Address()
        institution_stub.photo_url = "app/images/institution.png"

        institution_stub.put()

        return institution_stub
示例#30
0
    def post(self):
        coordinates_str = self.request.get('coordinates')
        min_sum = self.request.get_range('min_sum')
        delivery_sum = self.request.get_range('delivery_sum')
        free_delivery_sum = self.request.get_range('free_delivery_sum')

        coordinates = ast.literal_eval(coordinates_str)

        ribs_num = len(coordinates) - 1

        delivery_zone = DeliveryZone()
        delivery_zone.sequence_number = DeliveryZone.generate_sequence_number()

        geo_ribs = []
        for i in range(0, ribs_num - 1):
            start_point = coordinates[i]
            end_point = coordinates[i + 1]

            geo_rib = GeoRib()
            geo_rib.point1 = GeoPt(lat=start_point[1], lon=start_point[0])
            geo_rib.point2 = GeoPt(lat=end_point[1], lon=end_point[0])
            geo_ribs.append(geo_rib)

        start_point = coordinates[ribs_num - 1]
        end_point = coordinates[0]
        last_rib = GeoRib()
        logging.debug('start_point: {}'.format(coordinates))
        last_rib.point1 = GeoPt(lat=start_point[1], lon=start_point[0])
        last_rib.point2 = GeoPt(lat=end_point[1], lon=end_point[0])

        delivery_zone.geo_ribs = geo_ribs

        lat, lon = get_mean_coordinate(geo_ribs)
        candidates = get_cities_by_coordinates(lat, lon)
        if candidates:
            logging.critical('CANDIDATES')
            address = candidates[0]['address']
            address_obj = Address(**address)
            address_obj.lat = lat
            address_obj.lon = lon
            candidates = get_areas_by_coordinates(lat, lon)
            if candidates:
                address_obj.area = candidates[0]['address']['area']
            delivery_zone.address = address_obj

        delivery_zone.search_type = ZONE
        delivery_zone.price = delivery_sum
        delivery_zone.min_sum = min_sum
        delivery_zone.free_delivery_sum = free_delivery_sum
        delivery_zone.put()

        self.redirect('/company/delivery/zone/list')