def ajax_share(request): user_id = request.user_id share_uuid = request.POST.get('share_uuid', '') last_share_uuid = request.POST.get('last_share_uuid', '') job_uuid = request.POST.get('job_uuid', '') recommend_uuid = request.POST.get('recommend_uuid', '') data = "" if job_uuid: # 分享职位详情 job_details = Job.objects.filter(uuid=job_uuid)[:1] if job_details: if last_share_uuid: shares = Share.objects.filter(uuid=last_share_uuid)[:1] if not shares: return HttpResponse("十分抱歉,获取上个人推荐信息失败,请重试。重试失败请联系客服人员") last_share_id = shares[0].id else: last_share_id = 0 job_share = Share(user_id=user_id, uuid=share_uuid, job_id=job_details[0].id, last_share_id=last_share_id) job_share.save() data = "ok" else: log.error("uid(%s) try to get not exsit job(%s), maybe attack" % (user_id, job_uuid)) return HttpResponse("十分抱歉,获取职位信息失败,请重试。重试失败请联系客服人员") if recommend_uuid: # 分享带录音的职位详情 recommends = MyRecommend.objects.filter(uuid=recommend_uuid)[:1] if recommends: if last_share_uuid: shares = Share.objects.filter(uuid=last_share_uuid)[:1] if not shares: return HttpResponse("十分抱歉,获取上个人推荐信息失败,请重试。重试失败请联系客服人员") last_share_id = shares[0].id else: last_share_id = 0 job_share = Share(user_id=user_id, uuid=share_uuid, recommend_id=recommends[0].id, last_share_id=last_share_id) job_share.save() data = "ok" else: log.error( "uid(%s) try to get not exsit recommend(%s), maybe attack" % (user_id, recommend_uuid)) return HttpResponse("十分抱歉,获取推荐信息失败,请重试。重试失败请联系客服人员") return HttpResponse(data, content_type='application/json')
def insertData(qiniukey): share = Share.query.filter(Share.share_qiniuurl == qiniukey).first() if share is None: share = Share(None, qiniukey) db_session.add(share) db_session.commit() return share
def share(): share_target = User.query.filter_by( username='******').first() # Now users can share image only with admin try: path = request.json['path'] img_id = PATTERN_IMG_ID.match(path).groups()[0] image = Image.query.filter_by(owner=current_user, id=img_id).first() if image: share = Share(image=image, shared_user=share_target) db.session.add(share) db.session.commit() # send_notification_mail(share_target, app.config.get("BASE_URL")+path) # implement before official release print(f'[*] share {path}') redis.rpush('query', path) redis.incr('queued_count') return jsonify({'result': 'ok'}), 200 except IntegrityError as e: print(e) return jsonify({'error': 'Already shared'}), 400 except Exception as e: print(e) return jsonify({'error': 'Internal Server Error'}), 400 return jsonify({}), 404
def my_notes(): user = User.query.filter_by(id=current_user.id).first() form = CreateNoteForm(meta={'csrf_context': session}) if form.validate_on_submit(): heading = form.heading.data title = form.title.data body = form.body.data public = form.public.data note = Note(title=title, heading=heading, body=body, owner=user, public=public) db.session.add(note) shares_list = {row.strip() for row in form.shares.data.split()} for user_name in shares_list: share = Share(note=note, user_name=user_name) db.session.add(share) db.session.commit() flash('Notatka została dodana', 'alert alert-success') notes = user.notes return render_template('my_notes.html', form=form, notes=notes)
def addshare(self, issuerID): """ Adds share details of specified share to database to database. Args: issuerID (str): ASX issued code of share to add. Returns: bool: True if sucessful, false if share doesn't exist or is already present. """ # Initialse session with self.sessionmanager() as session: # Check that share isn't already added to database share = session.query(Share).filter( Share.issuerID == issuerID).first() if share is not None: return False # Get share data from ASX address = ("https://www.asx.com.au/asx/1/company/" f"{issuerID}?fields=primary_share") asxdata = requests.get(address).json() # Check if share data was not retrieved successfully if asxdata.get('error_code'): return False # Create new share record share = Share( issuerID=asxdata['code'], fullname=asxdata['name_full'], abbrevname=asxdata['name_abbrev'], shortname=asxdata['name_short'], description=asxdata['principal_activities'], industrysector=asxdata['sector_name'], currentprice=float( asxdata['primary_share']['last_price']), marketcapitalisation=int( asxdata['primary_share']['market_cap']), sharecount=int( asxdata['primary_share']['number_of_shares']), daychangepercent=float( asxdata['primary_share']['change_in_percent']. strip('%'))/100, daychangeprice=float( asxdata['primary_share']['change_price']), daypricehigh=float( asxdata['primary_share']['day_high_price']), daypricelow=float( asxdata['primary_share']['day_low_price']), dayvolume=int( asxdata['primary_share']['volume']) ) # Add share to share table session.add(share) # Return true for success return True
def submit_code(): if request.method == 'POST': title = request.form.get('title') code = request.form.get('code') code_id = randint(100000, 99999999) find = Share.query.filter_by(code_id=str(code_id)).first() while find: code_id = randint(100000, 999999) find = Share.query.filter_by(code_id=str(code_id)).first() new_code = Share(title=title, code=code, code_id=code_id) db.session.add(new_code) db.session.commit() return jsonify(msg=True, code_id=code_id) else: return redirect(url_for('index'))
def _create_share(form): article = Article.query.filter_by(url=form.url.data).first() if not article: article = Article(form.url.data) article.save() user = User.query.filter_by(email=form.friend.data).first() if not user: user = User(form.friend.data) user.save() share = Share(current_user, user, article) share.save() parse_article(article, share) return "Successfully shared to %s" % user.get_name()
def addShare(self, user, channel, msg): ''' Add a user's shared key to the database ''' args = self.addShareParser.parse_args(msg.split()) shareName = ' '.join(args.name).lower() shareKey = args.key.upper() if Share.by_name(shareName) is None and Share.by_private_key(shareKey) is None: share = Share( name=shareName, creator=user.lower(), private_key=shareKey, description=' '.join(args.description) ) dbsession.add(share) dbsession.flush() returnMessage = "Succesfully added new share '%s' to database" % share.name else: returnMessage = "Share already exists with that name or key" self.display(user, channel, returnMessage)
def post_share(user, obj): ''' ''' v = Share.objects.filter(user=user, object_id=obj.id) if v: return v[0] if user == obj.user: return True d = Dynamic(column=user.userprofile.get_column(), content_object=obj) share = Share(user=user, content_object=obj) if isinstance(obj, Link): d.way = WAY_LINK_SHARE share.way = 'l' elif isinstance(obj, Discuss): d.way = WAY_DISCUSS_SHARE share.way = 'd' elif isinstance(obj, Comment): share.way = 'c' share.comment_object = obj.content_object if isinstance(obj.content_object, Link): d.way = WAY_LINK_COMMENT_SHARE d.comment_object = obj.content_object elif isinstance(obj.content_object, Discuss): d.way = WAY_DISCUSS_COMMENT_SHARE d.comment_object = obj.content_object else: return False else: return False d.save() obj.n_share += 1 obj.save() UserData.objects.filter(user=user).update(n_shares=F('n_shares') + 1) share.save() return share
def get(self): client_id = int(self.request.headers.get('Client-Id') or 0) if not client_id: self.abort(400) client = Client.get(client_id) if not client: self.abort(400) if not config.SHARE_INVITATION_ENABLED: self.abort(403) share = Share.query(Share.sender == client.key, Share.status == Share.ACTIVE, Share.share_type == branch_io.INVITATION).get() logging.info('Found share: %s' % share) if share and not share.promo_code and not share.channel_urls: self.abort(412) if not share: share = Share(share_type=branch_io.INVITATION, sender=client.key) share.put() # need share id if 'iOS' in self.request.headers["User-Agent"]: user_agent = 'ios' elif 'Android' in self.request.headers["User-Agent"]: user_agent = 'android' else: user_agent = 'unknown' urls = [{ 'url': branch_io.create_url(share.key.id(), branch_io.INVITATION, channel, user_agent), 'channel': channel } for channel in branch_io.CHANNELS] share.channel_urls = [ChannelUrl(url=url['url'], channel=url['channel']) for url in urls] group_promo_codes = PromoCodeGroup() group_promo_codes.put() promo_code = PromoCode.create(group_promo_codes, KIND_SHARE_INVITATION, 100000, title=u'Переход по совету друга') share.promo_code = promo_code.key share.put() self.render_json({ 'text': config.SHARE_INVITATION_MODULE.invitation_text, 'urls': [channel_url.dict() for channel_url in share.channel_urls], 'image': config.SHARE_INVITATION_MODULE.invitation_image, 'promo_code': share.promo_code.id() })
def success(self, sender, gift, promo_code, sender_phone, sender_email, reciptient_name, recipient_phone): share = Share(share_type=branch_io.GIFT, sender=sender.key) share.put() if 'iOS' in self.request.headers["User-Agent"]: user_agent = 'ios' elif 'Android' in self.request.headers["User-Agent"]: user_agent = 'android' else: user_agent = 'unknown' recipient = { 'name': reciptient_name, 'phone': recipient_phone } url = branch_io.create_url(share.key.id(), branch_io.INVITATION, branch_io.SMS, user_agent, recipient=recipient) share.channel_urls = [ChannelUrl(channel=SMS, url=url)] share.put() gift.share_id = share.key.id() gift.put() text = u'Вам подарок от %s в приложении %s! Установите его: %s или введите в нем промо-код %s' % \ (sender_phone, config.APP_NAME, url, promo_code.key.id()) self.render_json({ 'success': True, 'sms_text': text })
def share(request): """ 点击分享,分享包括代码,当前结果(指数,图表), ajax方法,成功后返回生成的唯一url :param request: strategy_id 策略id svg_content svg dom元素 <svg>...</svg> result_params table dom元素 <table>...</table> title 分享帖子的标题 comment_content 分享帖子的content :return: """ if request.method == 'POST': account_info = request.session.get('account') account = Account.objects.get(id=account_info['id']) strategy_id = request.POST.get("strategy_id") strategy = Strategy.objects.get(id=strategy_id) #生成唯一url # /share/<identifier> # identifier由account id strategy id time hash 成 date = datetime.now() share_code = md5('_'.join([ str(account_info['id']), strategy_id, date.strftime("%Y%m%d%H%M%S") ])).hexdigest() result_params = request.POST.get('result_params') svg_content = request.POST.get('svg_content') #保存分享时代码 share_code_path = store_share_code(account_info['id'], strategy_id, strategy.file_path, share_code) if share_code_path is None: return HttpResponse( json.dumps({ 'status': 'error', 'data': u'分享失败' })) share = Share(account_id=account, strategy_id=strategy, url=share_code, date=date, share_code_path=share_code_path, result_params=result_params, svg_content=svg_content) try: share.save() #分享链接成功后调接口发帖 title = request.POST.get('title', u'策略分享') comment_content = request.POST.get('comment_content', '') content = concat_comment( comment_content, { 'code': get_share_code(share_code_path), 'result_params': result_params, 'svg_content': svg_content }) comment_id, flag = post_comment(account_id=account_info['id'], title=title, content=content) if not flag: return HttpResponse( json.dumps({ 'status': 'error', 'data': '分享链接失败' })) return HttpResponse( json.dumps({ 'status': 'ok', #TODO 'data': u'分享成功,快去社区看看吧' })) except Exception, e: social_log.error("==========Social Error", e) return HttpResponse( json.dumps({ 'status': 'error', 'data': u'生成分享链接失败' }))
def repost_user(quote_id,poet_id): """Repost a user quote""" share = Share(poet_id=poet.id, quote_id=quote_id, is_user_quote=True) db.session.add(share) db.session.commit()
def repost_fam(content,author,poet): """Repost an api quote""" quote = Quote.handle_api_quote(content=content,author=author) share = Share(poet_id=poet.id, quote_id=quote.id,is_user_quote=False) db.session.add(share) db.session.commit()
def generatetestshare(self, issuerID=None, fullname=None, shortname=None, abbrevname=None, description=None, industrysector=None, currentprice=None, marketcapitalisation=None, sharecount=None, daychangepercent=None, daychangeprice=None, daypricehigh=None, daypricelow=None, dayvolume=None): """ Helper method for creating a test share with specified attributes. If a share attribute is not defined, a random value will be generated and assigned instead. Args: All attributes of Share object, all default to none and will be generated for the Share unless assigned a value. Returns: A Share object with the given and generated attributes. """ # Generate values for each attribute if one is not assigned. if not issuerID: issuerID = ''.join(random.choices(string.ascii_uppercase, k=3)) if not fullname: fullname = ''.join(random.choices(string.ascii_lowercase, k=10)) if not shortname: shortname = ''.join(random.choices(string.ascii_lowercase, k=10)) if not abbrevname: abbrevname = ''.join(random.choices(string.ascii_lowercase, k=10)) if not description: description = ''.join(random.choices(string.ascii_lowercase, k=50)) if not industrysector: industrysector = ''.join( random.choices(string.ascii_lowercase, k=10)) if not currentprice: currentprice = round(random.uniform(1.0, 1000.0), 2) if not marketcapitalisation: marketcapitalisation = random.randint(1000000, 1000000000) if not sharecount: sharecount = random.randint(1000000, 1000000000) if not daychangepercent: daychangepercent = round(random.uniform(-1.0, 1.0), 2) if not daychangeprice: daychangeprice = round(random.uniform(1.0, 100.0), 2) if not daypricehigh: daypricehigh = round(random.uniform(currentprice, 1000.0), 2) if not daypricelow: daypricelow = round(random.uniform(1.0, currentprice), 2) if not dayvolume: dayvolume = random.randint(1000, 10000000) # Create share share = Share(issuerID=issuerID, fullname=fullname, abbrevname=abbrevname, shortname=shortname, description=description, industrysector=industrysector, currentprice=currentprice, marketcapitalisation=marketcapitalisation, sharecount=sharecount, daychangepercent=daychangepercent, daychangeprice=daychangeprice, daypricehigh=daypricehigh, daypricelow=daypricelow, dayvolume=dayvolume) # Return generated share return share