def create_item(username, itemname, kwargs): thing = Thing(owner=username, name=itemname) for key, value in kwargs.items(): setattr(thing, key, value) thing.save() print thing, 'saved with _id', thing._id
def main(): make_dir("things") chunks = build_chunks() for chunk in chunks: headers = get_headers() futures = [fetch.remote(thing_id, headers) for thing_id in chunk] results = ray.get(futures) Thing.insert_many(results).on_conflict_replace().execute()
def add_things(self, user): # Add 10 Things things = [ 'read War and Peace', 'sky dive', 'learn to SCUBA dive', 'get a university degree', 'learn to sail', 'learn to kite board', 'learn to play guitar', 'learn archery', 'learn spanish', 'learn chinese', ] self.response.out.write('<hr/>Adding things to do<hr/>') # Get all list items for the current user query = UserListItems.gql('WHERE user = :user', user=user) user_list_items = query.get() if user_list_items is None: user_list_items = UserListItems(user=user) for name in things: thing = Thing() thing.title = name thing.put() # Add Reference to the Thing from User user_list_item = UserListItem() user_list_item.user = user user_list_item.list_item = thing # Update the list of items the user has user_list_items.list_items.append(thing.key()) # Add the specifics of the user list item linkage user_list_item = UserListItem() user_list_item.user = user user_list_item.list_item = thing one_year = datetime.timedelta(days=365) today = datetime.datetime.today() user_list_item.date_due = today + one_year user_list_item.put() self.response.out.write('Added %s<br/>' % thing)
def log_recommendation(recommendation, recommended_by, notes, location, kind, url, when): with get_values(recommendation, recommended_by, notes, location, kind, url, when) as values: recommendation, recommended_by, notes, location, kind, url, when = values when = when.strip() if when: when = parse_timestr(when) with Base.get_session() as sess: thing = Thing.get_row(recommendation, recommended_by, kind, sess) if abs(datetime.datetime.now() - thing.modified_at).total_seconds() > 1: html_display_of_duplicate_recommendation.value = str(thing) #run_search(thing.name).to_html() message = "an entry with this thing.name already exists" raise Exception(message) thing.notes = notes thing.location_str = location thing.url = url if when: thing.created_at = when sess.commit() return
def get_thing(thing_id): thing = Thing.get(thing_id) print '{key}: {val}'.format(key='_id', val=thing._id) print '{key}: {val}'.format(key='_rev', val=thing._rev) for key in thing.all_properties().keys(): print '{key}: {val}'.format(key=key, val=getattr(thing, key))
def list_things(): header = '{:35s} {:15s} {:15s}'.format('Id', 'Owner', 'Name') print header print '=' * len(header) things = Thing.view('things/by_owner_name', include_docs=True, reduce=False) for thing in things: print '{:35s} {:15s} {:15s}'.format(thing._id, thing.owner, thing.name)
def home(request): """Home view with a little introduction and maybe some aggregate data.""" recent_opinions = Opinion.objects.all()[:10] recent_versus = VersusOpinion.objects.all()[:10] recent = sorted(list(recent_opinions) + list(recent_versus), key=lambda r: r.date, reverse=True)[:10] random_things = Thing.get_random() return render_to_response('opinions/home.html', {'recent_opinions': recent, 'random_things': random_things}, context_instance=RequestContext(request))
def get_status(): header = '{:35s} {:15s} {:15s}'.format('Id', 'Owner', 'Status') print header print '=' * len(header) things = Thing.view('things/status', group_level=2) for result in things: print '{:35s} {:15s} {:15s}'.format(result['key'][1], result['key'][0], result['value'])
def list_things(): header = '{:15s} {:8s}'.format('Owner', '# Things') print header print '=' * len(header) owners = Thing.view('things/by_owner_name', group_level=1) for owner_status in owners: owner = owner_status['key'][0] thing_count = owner_status['value'] print '{:15s} {:8d}'.format(owner, thing_count)
def get_status(): header = '{:35s} {:15s} {:15s}'.format('Id', 'Owner', 'Status') print header print '=' * len(header) things = Thing.view('things/status', group_level = 2 ) for result in things: print '{:35s} {:15s} {:15s}'.format(result['key'][1], result['key'][0], result['value'])
def build_chunks(): existing_records = list(Thing.select(Thing.id)) existing_ids = [record.id for record in existing_records] naive_range = list(range(START_ID, END_ID)) diff = list(set(naive_range) - set(existing_ids)) return [ diff[i * CHUNK_SIZE:(i * CHUNK_SIZE) + CHUNK_SIZE] for i in range(ceil(len(diff) / CHUNK_SIZE)) ]
def index(): things = Thing.query.filter_by(status=True).order_by( Thing.timestamp.desc()).all() form = to_do_Form() if form.validate_on_submit(): body = form.body.data thing = Thing(body=body) db.session.add(thing) db.session.commit() flash('待办事项已经添加!') return redirect(url_for('index')) return render_template('index.html', form=form, things=things)
def lend_thing(username, thing_id, to_user): try: thing = Thing.get(thing_id) except ResourceNotFound: print 'Thing not found' return lending = Lending(thing=thing_id, owner=username, to_user=to_user) lending.save() print lending, 'saved with _id', lending._id
def setUp(self): thing1 = Thing(name="Thing1") thing1.save() thing1 = Thing.objects.get(name="Thing1") thing2 = Thing(name="Thing2") thing2.save() thing2 = Thing.objects.get(name="Thing2") v = DataPoint(value={"state":"open"}, thing=thing1) v.save() v = DataPoint(value={"state":"closed"}, thing=thing1) v.save() v = DataPoint(value={"state":"frobbed"}, thing=thing1) v.save() v = DataPoint(value={"state":"closed"}, thing=thing1) v.save() v = DataPoint(value={"state":"frobbed"}, thing=thing1) v.save() v = DataPoint(value={"state":"closed"}, thing=thing1) v.save() v = DataPoint(value={"state":"frobbed"}, thing=thing1) v.save() v = DataPoint(value={"state":"blipped"}, thing=thing2) v.save() v = DataPoint(value={"state":"blipped"}, thing=thing2) v.save() v = DataPoint(value={"state":"blipped"}, thing=thing2) v.save()
def list_things(): header = '{:15s} {:8s}'.format('Owner', '# Things') print header print '=' * len(header) owners = Thing.view('things/by_owner_name', group_level = 1 ) for owner_status in owners: owner = owner_status['key'][0] thing_count = owner_status['value'] print '{:15s} {:8d}'.format(owner, thing_count)
def callback(line): seq = line['seq'] doc = line['doc'] if doc.get('doc_type', None) == 'Thing': obj = Thing.wrap(doc) elif doc.get('doc_type', None) == 'Lending': obj = Lending.wrap(doc) else: # we also have other types of documents - _design docs return print '{:5d} {:s} {:s}'.format(seq, line['id'], obj)
def addPresent(user_id, wh_id, typeid=None): thing1 = Thing(avatar=1, name=u"邻仓主题T恤", time_saved=datetime.now(), typeid=1, gender=2, units=1, subtype_name=u"", user_belong_to_id=user_id, wh_in_id=wh_id, state=1, present_id=1, notes=u"新用户赠送") thing1.save() thing2 = Thing(avatar=1, name=u"邻仓主题书签", time_saved=datetime.now(), typeid=3, gender=2, units=1, subtype_name=u"书签", user_belong_to_id=user_id, wh_in_id=wh_id, state=1, present_id=2, notes=u"新用户赠送") thing2.save() if typeid: typeid = int(typeid) itemList = Thing.objects.filter(user_belong_to_id=user_id).filter( state=1).filter(typeid=typeid).order_by('-tid')[0:PAGECOUNT] else: logger.debug("123456789") itemList = Thing.objects.filter(user_belong_to_id=user_id).filter( state=1).order_by('-tid')[0:PAGECOUNT] return itemList
def addNewItem(request): character = request.POST.get("character", u'未知') timeAdd = datetime.now() typeid = request.POST.get("typeid", 7) typeid = int(typeid) gender = request.POST.get("gender", 2) gender = int(gender) avatar = request.FILES.get("avatar", None) if avatar: _hasAvatar = 1 else: _hasAvatar = 0 subtype_name = request.POST.get("subname", u"未知") user_belong_to_id = request.POST.get("uid", None) wh_in_id = request.POST.get("whid", None) _name = TYPECONSTANT[typeid] + "-" + subtype_name + "-" + character if not user_belong_to_id or not wh_in_id: return Jsonify({ "status": False, "error": 1101, "error_message": "信息不足, 请输入用户id以及仓库id。" }) thing = Thing(avatar=_hasAvatar, name=_name, time_saved=timeAdd, typeid=typeid, gender=gender, subtype_name=subtype_name, user_belong_to_id=user_belong_to_id, wh_in_id=wh_in_id, state=1) thing.save() _tid = thing.tid thing = model_to_dict(thing) del (thing['time_saved']) del (thing['state']) del (thing['user_belong_to']) if False: currentPath = AVATARPATH + str(_tid) + ".png" data = "" for chunk in avatar.chunks(): data += chunk try: state = Picture().uploadPicture(currentPath, data) if state: return Jsonify({ "status": True, "error": "", "error_message": "", "tid": _tid }) else: logger.error("1109 UPYUN UPLOAD FAILED") try: _user = User.objects.get(uid=user['uid']) _user.avatar = False _user.save() except Exception, e: logger.error(e) logger.error("1109 User Acquirement Fail") return Jsonify({ "status": False, "error": "1109", "error_message": "图片上传失败, 使用默认图片。", "thing": thing }) except Exception, e: logger.error("upload error") logger.error(e) return Jsonify({ "status": False, "error": "1109", "error_message": "图片上传失败, 使用默认图片。" })
connections = set() #Ininial data #Setup DB dbconn = sqlite3.connect('db.sqlite3') cursor = dbconn.cursor() cursor.execute('''CREATE TABLE if not exists things (pk INTEGER PRIMARY KEY, name TEXT UNIQUE, img TEXT)''') cursor.execute('''CREATE TABLE if not exists items (pk INTEGER PRIMARY KEY, x INTEGER, y INTEGER, name TEXT, count INTEGER, UNIQUE (x, y, name))''' ) cursor.execute('''DELETE FROM things''') cursor.execute('''DELETE FROM items''') dbconn.commit() #Create 2 fruit apple = Thing('apple', '/media/img/apple.png') banana = Thing('banana', '/media/img/banana.png') apple.create(cursor, dbconn) banana.create(cursor, dbconn) #Create stock stock = Stock(3, 3, ['banana', 'apple']) #Fill all cells [i.create(cursor, dbconn) for i in stock] #Image dict for frontend images = {} [images.setdefault(i.name, i.img) for i in [apple, banana]] class WebSocketHandler(WebSocketHandler): # accept all cross-origin traffic