Exemplo n.º 1
0
    def cancelBooking(self, userEmail: str, bookingId: int):
        """
            Cancel a flight for a given user
        """
        allBookings, userBookings = self.showBookedFlights(userEmail,
                                                           methodCall=True)

        dateFormat = "%d-%m-%Y"
        notFound = True
        cancelledBooking = None
        for booking in allBookings:
            if booking["email"] == userEmail and booking[
                    "id"] == bookingId and booking["isActive"]:
                departureDate = datetime.strptime(booking["flight"]["date"],
                                                  dateFormat).date()
                todayDate = datetime.now().date()
                notFound = False
                if departureDate <= todayDate:
                    print(
                        'Cannot cancel the booking, because the departure date is too close.'
                    )
                    return
                booking["isActive"] = False
                cancelledBooking = booking
        if notFound:
            print('Not a valid bookingId')
            return

        bookingsPath = 'data/bookings.json'
        if cancelledBooking:
            writeBookings = self.file.writeJsonFile(bookingsPath, allBookings)
            print('Activating Mail Service')
            sendMail(userEmail, cancelledBooking["bookingId"],
                     cancelledBooking["flight"], False)
            print(" -- Flight Cancellation successful -- ")
Exemplo n.º 2
0
def checkPrice(url,paramPrice):
    headers={
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.55"
    }

    page = requests.get(url, headers=headers)

    htmlPage = BeautifulSoup(page.content,'html.parser')

    productTitle=htmlPage.find("h1", class_="pr-new-br").getText()

    price = htmlPage.find("span",class_="prc-slg").getText()

    image = htmlPage.find("img", class_="ph-gl-img")

    convertedPrice = float(price.replace(",",".").replace(" TL",""))

    if(convertedPrice <= paramPrice):
        print("Ürün fiyatı düştü")
        htmlEmailContent= """\
            <html>
            <head></head>
            <body>
            <h3>{0}</h3>
            <br/>
            {1}
            <br/>
            <p>Ürün linki: {2}</p>
            </body>
            </html>
            """.format(productTitle, image, url)
        sendMail("KIME_EMAIL","Ürünün fiyatı düştü👍👍", htmlEmailContent)
    else:
        print("ürün fiyatı düşmedi")
Exemplo n.º 3
0
def register(request):
    """注册用户"""
    if request.method == "POST":
        f = RegisterForm(request.POST)

        if f.is_valid():
            vari = request.POST.get('vari')
            if not vari or vari != request.session.get("captcha"):
                # return render(request, "register.html", {'errors': f.errors})
                return render(request, "register.html", {'errors': '错误的验证码'})
            name = f.cleaned_data["name"]    # 用户名
            email = f.cleaned_data["email"]  # 邮箱
            psd = f.cleaned_data["psd"]  # 密码
            real_ip = request.META['REMOTE_ADDR']   # ip
            introduction = f.cleaned_data["introduction"]
            vericode = hashlib.sha1(email+EMAIL_SALT).hexdigest()
            user = User.objects.create(name=name, email=email, psd=hashlib.sha1(psd).hexdigest(),
                                       introduction=introduction, vericode=vericode, real_ip=real_ip,
                                       image=DEFAULT_IMAGE_PATH)

            if sendMail([email], '验证邮箱', u"""{username},你好,IFORJ是致力于python的网络问答社区,帮助你寻找答案,分享知识。iforj是由用户可以根据自身的需
求,有针对性地提出问题;同时,这些答案又将作为搜索结果。你可以搜索类似的问题,问题被分为,爬虫,数据分析,django,scrapy,
python语法等基础分类,你可以按着分类搜索相关的问题。我们以打造最活跃的python问答平台为目的,很高兴为您提供便捷的服务。
如果有好的意见和建议,欢迎联系我们
<a href="http://{HOSTNAME}/validate/{vericode}">验证邮箱</a>""".format(username=name,
                    HOSTNAME=HOSTNAME, vericode=vericode)):
                del request.session['captcha']
                user.save()
            else:
                pass  # 邮件发送失败
            return HttpResponseRedirect("/")
        else:
            return render(request, "register.html", {'errors': f.errors})
    return render(request, "register.html")
Exemplo n.º 4
0
def git_pull():
    try:
        global logger, p
        j = request.json # payload
        if p.GIT_CI.save_payload:
            with open(os.path.join(Dirs()['LOG'],'git_payload_{}.pcl'.format(str(datetime.datetime.now()))), 'wb') as f:
                pickle.dump(j, f)

        #checking payload
        if j['head_commit']['committer']['email'] != p.GIT_CI.check_committer:
            Speak('commit security check not passed')
            logger.error('commit security check not passed')
            return 'commit security check not passed'

        process = Popen('git pull'.split(' '), stdout=PIPE, stderr=PIPE, cwd=Dirs()['REPO'])
        reply  = ' : '.join([str(i) for i in process.communicate() ])
        logger.info(reply)
        if p.GIT_CI.report_speak:
            Speak('git pull done on the machine {}'.format(socket.gethostname()))
        if p.GIT_CI.report_pull_email:
            sent = sendMail([p.email.address], [p.email.address, p.email.login, p.email.password], 'CI - git pull from ' + socket.gethostname(), reply ,[])
            logger.info(str(sent))
        return reply
    except Exception as e:
        logger.error(e)
        return 'error ' + str(e)
Exemplo n.º 5
0
def send(config, dmp_check):
    logger.info('attaching files:\n' + '\n'.join(files_to_backup(config)))
    logger.info('sending email ... ' + \
                sendMail([p.email.address], \
                         [p.email.address, p.email.login, p.email.password],\
                         'archive from ' + socket.gethostname(), \
                         str(files_to_backup(config)) + '\n' + dmp_check, \
                         files_to_backup(config)))
Exemplo n.º 6
0
 def book_stadium(self, book_time):
     self.driver.find_element_by_xpath(
         '//*[@class="business-order"]/div').click()  # 点击立即预定按钮,打开新页面
     sleep(3)
     n = self.driver.window_handles  # 获取当前页句柄
     self.driver.switch_to.window(n[1])  # 切换到新的网页窗口
     self.book_time(book_time)
     sleep(3)
     # 定位你要定的时间段
     while True:
         for i in range(4, 10):  # 我只需要预定第4列和第9列的场地,也就是4号到9号场地
             site = self.driver.find_element_by_xpath(
                 '//*[@id="booking"]/div[3]/div[1]/'
                 'table/tbody/tr[9]/td[{}]'.format(i))
             sta = site.get_attribute('status')
             if int(sta) != 0:
                 print('%s号场地已被预定' % i)
             else:
                 site.click()  # 场地可预订的话点击场地
                 sleep(3)
                 self.driver.find_element_by_xpath(
                     '//*[@id="booking"]/div[3]/div[2]/div[2]/a').click(
                     )  # 点击提交订单按钮
                 # 加上登录态失效时的判断,提交订单后,如果弹出登录页面,也会发送邮件给自己提醒场地有空出来
                 head = self.driver.find_element_by_class_name('headText')
                 if head:
                     print('登录态已失效,%s号场地还有,请登录预定!!' % i)
                     send_email.sendMail()
                     self.driver.quit()
                     return
                 sleep(2)
                 scroll_bottom = "window.scrollTo(0,document.body.scrollHeight)"  # 获取body的高度,滑到底部
                 self.driver.execute_script(scroll_bottom)
                 self.driver.find_element_by_xpath(
                     '//*[@class="order"]/a').click()
                 sleep(2)
                 self.driver.find_element_by_xpath(
                     '//*[@id="pay_form"]/div[1]/div[5]/div').click()
                 sleep(3)
                 print('%s号场地预定成功,请马上支付!!' % i)
                 send_email.sendMail()
                 self.driver.quit()
                 return
         sleep(int(format(random.randint(600, 1200))))  # 随机等待10-20分钟
         self.driver.refresh()
Exemplo n.º 7
0
Arquivo: iss.py Projeto: ignalex/pi
def Alert(distance):
    global alert_time, iss
    if distance <= alert_distance:
        if (datetime.datetime.now() - alert_time).seconds > 5 * 60 :
            alert_time = datetime.datetime.now()
            if alert_type == 'speak' and alert_time.hour > alert_time_window[0] and alert_time.hour < alert_time_window[1]:
                Speak("international space station approaching, distance is {0} kilometers".format(str(distance)))

        alert_message = '\t'.join([str(i) for i in [str(datetime.datetime.now()).split('.')[0], distance, iss.latitude, iss.longitude]])
        print (alert_message, file=open(os.path.join(Dirs()['LOG'], 'iss_alert'),'a'))
        logger.info(alert_message)
        logger.info('sending email ... ' + sendMail([p.email.address], [p.email.address, p.email.login, p.email.password], 'ISS approaching alert ', alert_message ,[]))
Exemplo n.º 8
0
def register(request):
    """注册用户"""
    if request.method == "POST":
        f = RegisterForm(request.POST)
        if f.is_valid():
            name = f.cleaned_data["name"]   # 用户名
            email = f.cleaned_data["email"] # 邮箱
            psd = f.cleaned_data["psd"] # 密码
            real_ip = request.META['REMOTE_ADDR']   #ip
            introduction = f.cleaned_data["introduction"]
            vericode = hashlib.sha1(email+EMAIL_SALT).hexdigest()
            user = User.objects.create(name=name, email=email, psd=hashlib.sha1(psd).hexdigest(),
                                       introduction=introduction, vericode=vericode, real_ip=real_ip)
            if sendMail([email], '验证邮箱', '<a href="http://{HOSTNAME}/validate/{vericode}">验证邮箱</a>'.format(HOSTNAME=HOSTNAME, vericode=vericode)):
                user.save()
            else:
                pass# 邮件发送失败
            return HttpResponseRedirect("/")
        else:
            return render(request, "register.html", {'errors': f.errors})
    return render(request, "register.html")
Exemplo n.º 9
0
    def bookAFlight(self, userEmail: str):
        """
            Book a flight for a given user
        """
        source = input("Enter the source: ")
        destination = input("Enter the destination: ")

        if not source or not destination:
            print("Invalid Inputs")
            return

        allFlights, availableFlights = self.getFlights(source,
                                                       destination,
                                                       display=True)

        if not availableFlights:
            return
        flightId = input("Enter the Flight Id: ")
        if not flightId.isdigit():
            print("invalid Input")
            return

        flightId = int(flightId)

        flight = self.getFlightById(source, destination, flightId)

        if not flight:
            print('No Flight with the given id found!')
            return

        if flight["available"] <= 0:
            print("No Seats Available -- Try another Flight")
            return

        bookingsPath = 'data/bookings.json'
        flightsPath = 'data/flights.json'
        bookingId = f'{userEmail}-{flight["id"]}-{flight["date"]}'

        bookings = []

        out = self.file.readJsonFile(bookingsPath)

        if out['status'] == 200:
            bookings = out['data']

        id = 1
        if bookings:
            id = bookings[-1]['id'] + 1

        newBooking = dict()

        newBooking['id'] = id
        newBooking['bookingId'] = bookingId
        newBooking['flight'] = flight
        newBooking['email'] = userEmail
        newBooking['isActive'] = True

        bookings.append(newBooking)

        for flight in allFlights:
            if flight["id"] == flightId:
                print(flight)
                flight["available"] -= 1

        writeBookings = self.file.writeJsonFile(bookingsPath, bookings)

        writeFlights = self.file.writeJsonFile(flightsPath, allFlights)

        if writeBookings['status'] == 200 and writeFlights['status'] == 200:
            print('Activating Mail Service')
            sendMail(userEmail, bookingId, flight, True)
            print("Booking Successful")
            print()
        else:
            print('something went wrong')
Exemplo n.º 10
0
def mainMethod():
    util = StockUtils()
    sqlins = mysqlOp()

    #例子。。。。。。。。。。。。。。,如果如果遍历这个A股,调用 # stocklist = util.getAllStockList()
    pList = util.getStockPriceEachMonth('000001',
                                        True)  #False 返回是每个月的数据,True 是年的数据
    for i in pList:
        print i.code, i.name, '时间:' + i.month, '开始价格:' + i.startPrice, '结束价格' + i.endPrice, '最高价:' + i.maxPrice, '最低价:' + i.minPrice

    #
    print '\n========================================当前时间:%s===========================================' % datetime.today(
    )
    print '\n===============================================近60天创新高======================================================'
    mh = util.get60DaysMaxStockList()
    print '===============================================共 %s 个======================================================' % str(
        len(mh))
    if mh and len(mh) > 0:
        mailString = (
            '===================================当前日期%s=================================='
            % str(datetime.today())[0:10])
        maxPriceList = []
        needSync = False
        fileName = 'stockMaxFile'
        #读取本地数据
        if fpath.exists(fileName):
            f = open(fileName, 'rb')
            allData = pickle.load(f)
            maxPriceList = allData['data']
            date = allData['date']
            if str(datetime.today())[0:10] != date or not date:
                needSync = True
            f.close()
        else:
            needSync = True
            f = open(fileName, 'w')
            f.close()
        for code in mh:
            if needSync:
                if len(maxPriceList) > 0:
                    maxCount = 0
                    for d in maxPriceList:
                        if d.has_key(code):
                            maxCount = int(d[code]) + 1
                            d[code] = maxCount
                            break
                        else:
                            continue
                        # maxPriceList.append({'code': code, 'maxPriceCount': '1'})
                    if maxCount == 0:
                        maxPriceList.append({code: '1'})
                else:
                    maxPriceList.append({code: '1'})
            else:
                pass
            model = szyjl(code)
            if not model: continue
            s1 = model.code.ljust(8, ' ') + model.name.ljust(
                6, ' ') + szyjlString(model)
            s2 = util.roeStringForCode(code, model)[0]
            s3 = util.roeStringInYearsForCode(code, model)[0]
            if s1 and s2 and s3:
                mailString = mailString + s1 + s2 + s3 + '\n\n'
                print s1
                print s2
                print s3
            else:
                pass

        if needSync:
            pprint.pprint(maxPriceList)
            f = open(fileName, 'w')
            pickle.dump(
                {
                    'data': maxPriceList,
                    'date': str(datetime.today())[0:10]
                }, f)
            f.close()
        else:
            pass

        # 发送邮件
        try:
            if mailString: sendMail(None, None, 'stock60Days', mailString)
        except Exception:
            print Exception.__name__
        finally:
            print ''

    #价值投资选股
    print '\n===============================价值投资股票========================================'
    th = util.getMostValueableStockList()
    myStock = []
    if th and len(th) > 0:
        print '===============================共 %s 个========================================\n' % str(
            len(th))
        for item in th:
            model = szyjl(item.code)
            rankModel = szyjlRank(item.code)
            if not model or not rankModel: continue
            #不需要过滤换手率以及市值,价值投资
            print(u'第%s个:' % str(th.index(item) + 1)), item.name.ljust(
                6, ' '), item.code.ljust(7, ' '), mostValueableCompanyString(
                    item), szyjlString(model), szyjlRankString(rankModel)
            jidu = util.roeStringForCode(item.code, model)
            niandu = util.roeStringInYearsForCode(item.code, model)
            if jidu and niandu:
                if niandu[1]:
                    print '=======================================高速增加,可以关注======================================='
                if niandu[2]:
                    print '=======================================高潜质企业,可以关注======================================='
                if niandu[3]:
                    print '=======================================高附加值,可以关注======================================='
                if (niandu[1] or niandu[3]):
                    myStock.append(item)
                print jidu[0]
                print niandu[0]
            else:
                continue

    if len(myStock) > 0:
        print '\n\n\n'
        print '=======================================高成长企业列表,强烈关注============================================='
        print '=======================================高成长企业列表,强烈关注============================================='
        print '=======================================高成长企业列表,强烈关注============================================='
        ret = sorted(myStock, key=lambda item: item.jzcsyl, reverse=True)
        for i in ret:
            if float(i.jzcsyl[0:-2]) / 100 <= float(0.12): continue
            model = szyjl(i.code)
            if model:
                print i.code, i.name, '机构持仓数:' + i.orgCount, '资产收益率:' + i.jzcsyl, '  ', szyjlString(
                    model)
                print util.roeStringForCode(i.code, model)[0]
                print util.roeStringInYearsForCode(i.code, model)[0]
                print util.getCompanyBussinessDetailString(i.code)
                print '\n\n'
            else:
                continue
        print '\n\n'

    # print '================================创新高绩优股========================================='
    # interList = list(set(mh).intersection(set([item.code for item in th])))
    # for code in interList:
    #     model = szyjl(code)
    #     print model.code,model.name
    #     print util.roeStringForCode(code,model)[0]

    #调研次数
    # print '\n=================================机构调研次数排行==================================='
    # dy = util.getCompanyResearchRank()
    # if dy and len(dy):
    #     for item in dy:
    #         print item.name, item.code, item.time, item.desc, item.sum
    #
    # #推荐公司
    # print '\n===============================券商推荐公司======================================='
    # tj = util.getRcommandedCompanyList()
    # if tj and len(tj):
    #     for item in tj:
    #         print item.code, item.name, item.time, item.org, item.reason, item.advice

    #推荐次数排行公司
    # print '\n======================================券商推荐次数排行============================================='
    # tj = util.getRcommandRankList()
    # if tj and len(tj):
    #     for item in tj:
    #         print item.code.ljust(9,' '),item.name.ljust(8,' '),('券商推荐次数:'+item.count + '  买入评级:' + item.buyCount + '  增持评级:' + item.addCount)
    #         model = szyjl(item.code)
    #         print util.roeStringForCode(item.code,model)
    #         print util.getCompanyBussinessDetailString(item.code)
    #         print '\n'

    # #股东增持
    print '\n====================================股东增持====================================='
    gd = util.getStockholderHoldsStocks()
    if gd and len(gd):
        for item in gd:
            companyInfo = item.split(',')
            print companyInfo[0], companyInfo[1].ljust(
                7, ' '), companyInfo[-4], u'至', companyInfo[-3], (
                    companyInfo[4]).ljust(
                        30,
                        ' '), companyInfo[5], (companyInfo[6] + u'万').ljust(
                            13,
                            ' '), (u'占流通股的' + (companyInfo[7] + '%')).ljust(
                                15,
                                ' '), (u'市值: ' + util.getSylDetailDataForCode(
                                    companyInfo[0]).sz + u'亿').ljust(15, ' ')

    # #行业报告
    # print '\n==================================行业涨幅分析报告================================='
    # hy = util.getIndustryReport()
    # if hy and len(hy):
    #     for item in hy:
    #         print item.split(',')[10],item.split(',')[-1],'   ', item
    #
    #
    # # #概念排行
    # print '\n=================================概念涨幅排行====================================='
    # lit = util.getIndustryRank()
    # if lit and len(lit):
    #     for item in lit:
    #         print item

    # #周k线图
    # print '\n=================================周K线图====================================='
    # stocklist = util.getAllStockList()
    # for item in stocklist:
    #     week = util.getWeekKLineForCode(item)
    #     print week

    #优质基金列表
    print '\n=================================优质基金====================================='
    fundList = util.getGoodFundList()
    companyRank = {}
    for i in fundList:
        print i.code, (i.name).ljust(20, ' '), ('一周收益:' + i.weekProfit).ljust(
            15, ' '), ('月收益' + i.oneMonthProfit).ljust(
                14, ' '), ('3个月收益:' + i.threeMonthProfit).ljust(
                    17, ' '), ('半年收益:' + i.halfYearProfit).ljust(
                        15, ' '), ('一年收益:' + i.oneYearProfit).ljust(
                            15,
                            ' '), ('3年收益:' + i.threeYearProfit).ljust(15, ' ')
        companyList = util.getFundHoldCompanyList(i.code)
        if companyList and len(companyList):
            for code in companyList:
                #code 最后一位是市场代码,沪市还是深市
                c = code[0:-1]
                model = szyjl(c)
                if model:
                    if companyRank.has_key(c):
                        v = companyRank[c]
                        companyRank[c] = str(int(v) + 1)
                    else:
                        companyRank[c] = "1"
                else:
                    continue
                # print model.code,model.name
    ret = sorted(companyRank.iteritems(),
                 key=lambda item: int(item[1]),
                 reverse=True)
    print '\n================ ===============持仓机构数量====================================\n'
    for item in ret:
        k = item[0]
        v = companyRank[k]
        weekModel = util.getWeekKLineForCode(k)
        rankModel = szyjlRank(k)
        price = ''
        if weekModel:
            price = (weekModel.priceList[-1]).endPrice
        print k, util.getStockNameFromCode(k), v, szyjlString(
            szyjl(k)), szyjlRankString(rankModel), (u'现价:' + price)
        model = szyjl(k)
        if model:
            print util.roeStringForCode(k, model)[0]
            print util.roeStringInYearsForCode(k, model)[0]
        else:
            pass

    print '\n\n'