def __init__(self, url, phone_num): self.phone_dict = {} # 需要获取的页数 page_num = phone_num // 8 + 1 for i in range(1, page_num + 1): phone_d = Phone(url.format(i)).get_phone() self.phone_dict.update(phone_d)
def contact_list(): """Show all contacts and add a contact into the database.""" contacts = Contact.query.all() if request.method == 'GET': return render_template('contact_list.html', contacts=contacts) elif request.method == 'POST': # Get form variables name = request.form.get('name') type = request.form.get('type') phone = request.form.get('phone') user_id = session.get('user_id') new_contact = Contact(name=name, user_id=user_id) new_phone = Phone(phone=phone, type=type) new_contact.phones.append(new_phone) db.session.add(new_contact) db.session.commit() flash(f"Contact {name} added.") return jsonify(new_contact.convert_to_dict())
def get(self, phoneID = None): phoneKey = None if phoneID is not None: query = Phone.all() query.filter("phoneid =", phoneID) results = query.fetch(1) if query.count(1) > 0: phoneKey = results[0].key() else: self.error(404) if phoneKey is not None: list = {} benchmark = {} query = Benchmark.all() query.order("-timestamp") # can cause extra CPU load query.filter("phonekey =", phoneKey) results = query.fetch(1000) benchmark["Benchmark"] = results list["list"] = benchmark; printJson(self, list) else: self.error(404)
def get_phone_data(self): mapping = self._read_mapping() current_offset = self.first_phone_record_offset while current_offset < len(self.buf): buffer = self.buf[current_offset:current_offset + self.phone_fmt_length] number, region_offset, phone_type = struct.unpack(self.phone_fmt, buffer) p = Phone(number=number, type=phone_type, region_id=mapping[str(region_offset)]) self.session.add(p) self.session.commit() current_offset += self.phone_fmt_length
def load_phones(): """ loads phones numbers of temples from a file. """ for row in open("seed_data/phonedata.txt"): print row row = row.rstrip() #phone_no_1, nothing, temple_id = row.split("\t") phonelist = row.split("\t") phone_no_1 = phonelist[0] temple_id = phonelist[2] #print len(listtest) phones = Phone(phone_no_1=phone_no_1, temple_id=temple_id) db.session.add(phones) db.session.commit()
def receive_phones(): ''' Receives either new phones or refurbished phones from manufacturing with replaced parts ''' phones = request.get_json() phone_type = '' if phones["phones"][0]["status"].lower() == 'new': phone_type = 'new' elif phones["phones"][0]["status"].lower() == 'refurbished': phone_type = 'refurbished' if phone_type == 'new': for phone in phones["phones"]: modelId = phone["modelID"] status = phone["status"] phone_to_add = Phone(status, modelId) db.session.add(phone_to_add) screen, battery, memory = phone["partIDs"] db_screen = Part.query.filter_by(id=screen).first() db_screen.phoneId = phone_to_add.id db_screen.used = True db_battery = Part.query.filter_by(id=battery).first() db_battery.phoneId = phone_to_add.id db_battery.used = True db_memory = Part.query.filter_by(id=memory).first() db_memory.phoneId = phone_to_add.id db_memory.used = True db.session.commit() elif phone_type == 'refurbished': for phone in phones["phones"]: phoneId = phone["phoneID"] db_phone = Phone.query.filter_by(id=phoneId).first() db_phone.status = "Refurbished" db_phone.refurbishedDate = datetime.datetime.now() screen, battery, memory = phone["partIDs"] broken = phone["broken"] db_broken = Part.query.filter_by(id=broken).first() db_broken.defective = True db_broken.phoneId = None db_broken.used = False db_screen = Part.query.filter_by(id=screen).first() db_screen.phoneId = phoneId db_screen.used = True db_battery = Part.query.filter_by(id=battery).first() db_battery.phoneId = phoneId db_battery.used = True db_memory = Part.query.filter_by(id=memory).first() db_memory.phoneId = phoneId db_memory.used = True db.session.commit() return app.make_response(('200', {'Content-Type': 'application/json'}))
def post(self): """ Registers user on database with JSON object data. Headers: Content-Type: application/json JSON Request format: { "nome": nome, "email": email, "senha": senha, "telefones": [ { "numero": numero, "ddd": ddd }, ... ] } """ data = sign_up_parser.parse_args() # Validate email if re.match("^[\w.]+@[\w]+\.[\w]+$", data.email) is None: return { 'mensagem': '{} não é um email válido.'.format(data.email) }, 400 # Email already registered if email_exists(data.email): return { 'mensagem': '{} já foi registrado.'.format(data.email) }, 400 # Validate phone numbers for phone in data['telefones']: if num.match(phone['numero']) is None or num.match( phone['ddd']) is None: return { 'mensagem': '{} {} não é um numero de telefone válido.'.format( phone['ddd'], phone['numero']) }, 400 # Create user ORM user = User(data['nome'], data['email'], User.generate_hash(data['senha'])) user.phones = [ Phone(phone['numero'], phone['ddd']) for phone in data['telefones'] ] # Generate token token = Log.generate_token( { 'sub': user.uuid, 'name': user.name, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30) }, app.config['SECRET_KEY']) # Add to database session.add(user) session.add(Log(user, token)) session.commit() # User registered successfully return { 'id': user.uuid, 'email': user.email, 'data_criacao': user.creation_date.isoformat(), 'data_atualizacao': user.update_date.isoformat(), 'ultimo_login': user_last_login(user.email).date.isoformat(), 'token': token.decode('UTF-8') }, 201
user_juan.user_settings.append(juan_mag_setting) #CREATE LOCATION location1 = Location(lat=37.776460, lng=-122.228150, address="3098 E 10th St, Oakland, CA 94601") user_fabio.locations.append(location1) location2 = Location(lat=37.787970, lng=-122.418470, address="683 Sutter St, San Francisco, CA 94109") user_juan.locations.append(location2) #CREATE PHONES home_jesus = Phone(phone=TEST_PHONE, type="home") cel_jesus = Phone(phone=TEST_PHONE, type="cel") cel_nati = Phone(phone=TEST_PHONE2, type="cel") home_nati = Phone(phone=TEST_PHONE2, type="home") #CREATE CONTACTS nati_contact = Contact(name="Nati") nati_contact.user = user_fabio nati_contact.phones.extend([cel_nati, home_nati]) marco_contact = Contact(name="Marco") marco_contact.user = user_fabio jesus_contact = Contact(name="Jesus") jesus_contact.user = user_juan
from sqlalchemy import create_engine from model import Person, Phone, Base # Create the database engine and session. engine = create_engine('sqlite:///roster.db') Session = sessionmaker(bind=engine) session = Session() # Create the database. Base.metadata.create_all(engine) print('Created the database and tables') # John Adams person = Person(first_name='John', last_name='Adams') phone = Phone(phone_number='555-1234', phone_type='home') person.phones.append(phone) phone = Phone(phone_number='555-5555', phone_type='cell') person.phones.append(phone) session.add(person) print('Added info for John Adams') # Sara Smith person = Person(first_name='Sara', last_name='Smith') phone = Phone(phone_number='555-9999', phone_type='cell') person.phones.append(phone) session.add(person) print('Added info for Sara Smith') # Richard Recluse person = Person(first_name='Richard', last_name='Recluse')
def post(self): post = simplejson.loads(self.request.body) phoneKey = None deviceKey = None brandKey = None benchmarkKey = None phoneID = None device = None brand = None totalScore = None testResults = [] # get post data try: phoneID = post["phoneid"] device = post["device"] brand = post["brand"] totalScore = int(post["total_score"]) testResults = post["results"] except KeyError: self.error(404) if phoneID is not None and device is not None and brand is not None and totalScore is not None and testResults: query = Phone.all() query.filter("phoneid =", phoneID) results = query.fetch(1) # get phone key if query.count(1) > 0: phoneKey = results[0].key() else: phoneKey = Phone( phoneid = phoneID ).put() query = Device.all() query.filter("name =", device) results = query.fetch(1) # get device key if query.count(1) > 0: deviceKey = results[0].key() else: query = Brand.all() query.filter("brandname =", brand) results = query.fetch(1) # get brand key if query.count(1) > 0: brandKey = results[0].key() else: # add brand brandKey = Brand( brandname = brand ).put() # add device deviceKey = Device( brandkey = Key(brandKey), name = device ).put() # new benchmark if phoneKey is not None and deviceKey is not None: benchmarkKey = Benchmark( phonekey = phoneKey, devicekey = deviceKey, total_score = totalScore ).put() if benchmarkKey is not None: for result in testResults: test = None testKey = None try: test = result["test"] except KeyError: self.error(404) # get test key query = Test.all() query.filter("name =", test) results = query.fetch(1) # get phone key if query.count(1) > 0: testKey = results[0].key() score = None successful = None try: score = int(result["score"]) successful = bool(result["successful"]) except KeyError: self.error(404) if testKey is not None and score is not None and successful is not None: # put test result testResultKey = TestResult( benchmarkkey = benchmarkKey, testkey = testKey, score = score, successful = successful ).put() if not testResultKey: self.error(405) break; else: self.error(404) else: self.error(404) else: self.error(404) else: self.error(404)