コード例 #1
0
ファイル: offer_loader.py プロジェクト: bloogrox/cpa-python
def tie_offer_to_app(offer):
    from app import db
    from app.models import App, Platform
    from app.utils.appstore_detector import detect_appstore_type, ITUNES, PLAY_GOOGLE

    appstore_type = detect_appstore_type(offer.preview_url)

    if appstore_type == ITUNES:
        from app.utils.itunes import extract_id_from_url
        app_id = extract_id_from_url(offer.preview_url)
    elif appstore_type == PLAY_GOOGLE:
        from app.utils.playgoogle import extract_id_from_url
        app_id = extract_id_from_url(offer.preview_url)
    else:
        return None

    if app_id:

        platform = Platform.get_by_appstore_type(appstore_type)

        app = App.query.filter(App.app_id == app_id, App.platform == platform).first()

        if not app:
            ### create app
            app = App()
            app.app_id = app_id
            app.platform = platform
            db.session.add(app)

        ### tie to app
        offer.app = app
        db.session.flush()

    else:
        return None
コード例 #2
0
ファイル: views.py プロジェクト: stanliski/dev_frame
def new_app():

    """
    用户创建APP
    """

    if check_user_login():
        return redirect(url_for('main.signin'))

    if request.method == 'GET':
        return render_template('new-app.html')

    app_name = request.form.get('app_name', '', type=str)
    platform = request.form.get('app_usage', -1, type=int)
    description = request.form.get('description', '', type=str)

    # 判断是否为空
    if app_name.strip() == '' or description.strip() == '':
        return jsonify({'status':400})

    developer = Developer.query.filter_by(username=session.get("username")).first()

    if description.strip() == '' or app_name.strip() == '':
        return render_template('new-app.html', warning='')

    app = App(app_name=app_name, description=description,
              platform=platform)

    app.developer = developer

    try:
        app.save()
    except Exception, e:
        print e
        return jsonify({'status':401})
コード例 #3
0
def appadd():
    form = AppForm()
    if request.method == 'POST' and form.validate_on_submit():
        var = App(name=request.form['name'], is_active='is_active' in request.form)
        db.session.add(var)
        db.session.commit()
        return redirect('/app/list')
    return render_template('appadd.html', form=form)
コード例 #4
0
ファイル: importcsv.py プロジェクト: shentonfreude/rostrum
def csv_to_db(csvfile):
    App.objects.all().delete()      # DANGER: Delete existing apps info
    reader = csv.DictReader(csvfile)
    num_apps = 0
    warnings = []
    infos = []
    for rid, row in enumerate(reader):
        acronym = row['Acronym'].strip()
        version = row['Version Number'].strip()
        if acronym == '':
            msg = "Ignoring row=%d without Acronym" % rid
            warnings.append(msg)
            logging.warning(msg)
            continue
        if len(acronym) < 2:
            msg = "Ignoring row=%d with too-short Acronym=%s" % (rid, acronym)
            warnings.append(msg)
            logging.warning(msg)
            continue
        existing = App.objects.filter(acronym__iexact=acronym, version_number=version)
        if existing:
            msg = "Ignoring extant acronym=%s version=%s" % (acronym, version)
            warnigns.append(msg)
            logging.warning(msg)
            continue
        app = App()
        app.save()                  # save for M2M
        for k, v in row.items():
            v = v.strip()
            if not v:           # don't store empty values
                continue
            # MAYBE TODO: filter nulls from M2M, check nullish
            # MAYBE TODO: transform Date, Time, Boolean, Integer
            try:
                setattr(app, mogrify(k), v)
            except (TypeError, ValidationError), e:
                logging.error("SETATTR: %s", e)
                import pdb; pdb.set_trace()
        try:
            app.save()
        except (TypeError, ValidationError), e:
                logging.error("SAVE: %s", e)
                import pdb; pdb.set_trace()
コード例 #5
0
def appaddtest():
    addcount = request.args.get('addcount', 20, type=int)
    for addone in range(addcount):
        var = App(name=f'name{addone}',
                  desc=f'desc{addone}',
                  is_active=0
                  )
        db.session.add(var)
    db.session.commit()
    return redirect('/list')
コード例 #6
0
ファイル: views.py プロジェクト: singpingwu/UploadSite
def app_add(request):
    # getAppBaseInfo(os.getcwd() + "/appStorage/Smart360.apk")
    try:
        if request.method == 'POST':
            upload_file = request.FILES.get('file')
            appName = request.POST['appName']
            buildName = request.POST['buildName']
            version = request.POST['version']
            release_note = request.POST['releaseNote']
            if not upload_file:
                raise FileNotFoundError("please upload file")
            isExists = Update.objects.filter(app_name=appName,
                                             build_name=buildName)
            if isExists:
                return HttpResponse("添加失败,该应用以存在,请在更新列表中进行更新即可")

            name = upload_file.name[0:-4] + "_" + buildName + "_" + str(
                version) + ".apk"
            upload_file_path = os.getcwd() + "/appStorage/" + name
            with open(upload_file_path, 'wb+') as destination:
                for chunk in upload_file.chunks():
                    destination.write(chunk)
            update = Update(app_name=appName,
                            build_name=buildName,
                            version=version,
                            size=upload_file.size,
                            release_note=release_note,
                            release_time=datetime.datetime,
                            storage_name=name)
            update.save()
            app = App(app_name=appName,
                      build_name=buildName,
                      version=version,
                      size=upload_file.size,
                      release_time=datetime.datetime,
                      storage_name=name)
            app.save()
            return HttpResponse("Add application success")
        else:
            return HttpResponse("Must use the POST method")
    except Exception as e:
        return HttpResponse("Add application failed. >>> ")
コード例 #7
0
def pump_apps_table():
    print('apps')

    apps = [
        ('ORDERING SRVC ADMIN',          1)
    ]

    for app, category_id in apps:
        try:
            app = App(name=app, app_category_id=category_id)
            AppsRoute.after_app_creation(app)
        except:
            pass
コード例 #8
0
        def decorated_func(*args, **kwargs):
            api_key = request.headers.get('api-key')

            if api_key is None:
                raise errors.UnauthorizedError(
                    '`api-key` must be sent in headers')

            app = App.get_active(api_key=api_key)

            if app is None:
                raise errors.BadRequest('`api-key` is invalid')

            return view_func(*args, **kwargs)
コード例 #9
0
ファイル: views.py プロジェクト: singpingwu/UploadSite
def upload_app(request):
    try:
        upload_file = request.FILES.get('file')
        version = request.POST['version']
        appName = request.POST['appName']
        buildName = request.POST['buildName']
        release_note = request.POST['releaseNote']
        if not upload_file:
            raise FileNotFoundError("please upload file.")
        updateApp = Update.objects.get(app_name=appName, build_name=buildName)
        if updateApp.version >= int(version):
            return HttpResponse("更新失败,新版本号小于当前版本")

        name = upload_file.name[:-4] + "_" + buildName + "_" + str(
            version) + ".apk"
        upload_file_path = os.getcwd() + "/appStorage/" + name
        with open(upload_file_path, 'wb+') as destination:
            for chunk in upload_file.chunks():
                destination.write(chunk)
        print(upload_file.size)
        updateApp.version = version
        updateApp.size = upload_file.size
        updateApp.release_note = release_note
        updateApp.release_time = datetime.datetime.now()
        updateApp.storage_name = name
        updateApp.save()

        app = App(app_name=appName,
                  build_name=buildName,
                  version=version,
                  size=upload_file.size,
                  release_time=datetime.datetime,
                  storage_name=name)
        app.save()
    except BaseException as e:
        return HttpResponse(e)

    return HttpResponse("upload success")
コード例 #10
0
ファイル: api.py プロジェクト: skempins-sjrwmd/PythonProjects
    def post(self):
        if not "app_id" in request.json or not "app_secret" in request.json:
            error = {"code": "MISSING_APP_ID_OR_APP_SECRET"}
            return jsonify({'error': error}), 400

        existing_app = App.objects.filter(app_id=request.json.get('app_id')).first()
        if existing_app:
            error = {"code": "APP_ID_ALREADY_EXISTS"}
            return jsonify({'error': error}), 400
        else:
            # create credentials
            salt = bcrypt.gensalt()
            hashed_password = bcrypt.hashpw(request.json.get('app_secret'), salt)
            app = App(app_id=request.json.get('app_id'), app_secret=hashed_password).save()
            return jsonify({'result':'ok'})
コード例 #11
0
ファイル: models.py プロジェクト: CriminalProject/Project2
    def setRestCounters(self):
        rules = App.getCR(App)
        period = rules.periodCounter
        totalPoints = 0
        for user in User.objects.all():
            totalPoints = period + totalPoints

        for rest in Restaurant.objects.filter(serviceStatus=True):
            points = Points.objects.filter(restaurant=rest)
            for point in points:
                serviceCounter = (point.point / totalPoints) * 100
                intServiceCounter = int(serviceCounter)
                if rest.serviceCounter == 0:
                    rest.serviceCounter = intServiceCounter
                    rest.save()

        Restaurant.serviceCounters(Restaurant)
        rules.save()
コード例 #12
0
    def updateRestStatus(self, newStatus, upRestName):
        rules = App.getCR(App)
        upRestaurant = self.objects.get(restName=upRestName)
        if rules.calculationCheck == True:
            if newStatus == False:
                activeCounter = self.objects.filter(
                    serviceCounter__gt=0, serviceStatus=True).count()
                counter = upRestaurant.serviceCounter
                if activeCounter != 0 and counter != 0:
                    for activeRest in self.objects.filter(
                            serviceCounter__gt=0,
                            serviceStatus=True).order_by('-serviceCounter'):
                        activeRest.serviceCounter = activeRest.serviceCounter + 1
                        activeRest.save()
                        counter = counter - 1
                        if counter == 0:
                            break
                else:
                    return False

            else:
                activeRests = self.objects.filter(serviceCounter__gt=0,
                                                  serviceStatus=True)
                activeCounter = self.objects.filter(
                    serviceCounter__gt=0, serviceStatus=True).count()

                counter = upRestaurant.serviceCounter
                if activeCounter != 0 and counter != 0:
                    for activeRest in self.objects.filter(
                            serviceCounter__gt=0,
                            serviceStatus=True).order_by('-serviceCounter'):
                        if activeRest.serviceCounter > 0:
                            activeRest.serviceCounter = activeRest.serviceCounter - 1
                            activeRest.save()
                            counter = counter - 1
                        if counter == 0:
                            break

                else:
                    return False

        upRestaurant.serviceStatus = newStatus
        upRestaurant.save()
        return True
コード例 #13
0
ファイル: model.py プロジェクト: AlexeyElizarov/connector
    def __init__(self, controller):
        self.controller = controller

        config = ConfigParser()
        config.read(self._config)

        # App default settings
        self.app = App(**config['DEFAULT'])

        # RDC handling
        if self.app.rdc:
            self.rdc = RDC[self.app.rdc.lower()]()

        # SAP landscape handling
        if self.app.sap:
            self.sap = SAP(self.app.sap)

        # VPN handling
        if self.app.vpn:
            self.vpn = VPN[self.app.vpn.lower()]()
コード例 #14
0
ファイル: views.py プロジェクト: CriminalProject/Project2
def statistics(request):
    rules = App.getCR(App)
    restList = []
    counter = 1
    userCount = User.objects.all().count()
    totalPoints = rules.calculationPeriod * userCount
    total =  Restaurant.objects.all().count()
    vehicleCount = Restaurant.objects.filter(modeOfTransport = True).count()
    pedestrianCount = Restaurant.objects.filter(modeOfTransport = True).count()
    aviableInBadWeather = Restaurant.objects.filter(weatherCondition = True).count()
    AnaviableInBadWeather = Restaurant.objects.filter(weatherCondition = False).count()
    activeRests = Restaurant.objects.filter(serviceStatus = True).count()
    inactiveRests = Restaurant.objects.filter(serviceStatus = False).count()
    infoList = [{'userCount':userCount,'totalPoints':totalPoints,'totalRests':total,'vehicleRests':vehicleCount,'pedestrianRests':pedestrianCount,'aviableInBadWeather':aviableInBadWeather,'AnaviableInBadWeather':AnaviableInBadWeather,'activeRests':activeRests,'inactiveRests':inactiveRests}]
    allCalculations = Calculation.objects.all().count()
    restNames = []
    restFlag = False
    for record in Calculation.objects.all():
                restFlag = False
                for restName in restNames:
                    if record.restaurant.restName == restName:
                        restFlag = True
                        break
                if restFlag == True:
                    continue
                restNames.append(record.restaurant.restName)
                restObject = Restaurant.objects.get(restName = record.restaurant.restName )
                rest = Calculation.objects.filter(restaurant = restObject).count()
                restPoint = Points.objects.filter(restaurant = restObject)
                finalPoint = 0
                for point in restPoint:
                    finalPoint = finalPoint+point.point
                row = {'restName':record.restaurant.restName,'wentCount':rest,'point' : finalPoint,'serviceCounter':restObject.serviceCounter,'modeOfTransport':restObject.modeOfTransport,'weatherCondition':restObject.weatherCondition,'serviceStatus':restObject.serviceStatus}
                restList.append(row)
                
    context = Context({'app':rules,'Calculation' : restList,'infoList':infoList})
    return render(request,'statistics.html',context)
        
    
コード例 #15
0
def new(request):
    CONFIG = config
    if request.method == 'POST':
        form = AppForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            name = form.cleaned_data['name']
            desc = form.cleaned_data['description']
            author = form.cleaned_data['author']
            version = form.cleaned_data['version']
            location = CONFIG.APP_DIRECTORY + request.FILES['file'].name
            
            anApp = App(name=name, description=desc, version=version, location=location, author=author)
            anApp.save()
            anApp.downloadLink = request.build_absolute_uri(reverse('app.views.download', kwargs={'id':anApp.id}))
            anApp.save()

            messages.add_message(request, messages.SUCCESS, 'Successfully Created')
            return HttpResponseRedirect('/app/')
    else:
        form = AppForm()
    return render(request, 'app/new.html', locals())
コード例 #16
0
ファイル: views.py プロジェクト: apixon/panex-web
def new(request):
    CONFIG = config
    if request.method == "POST":
        form = AppForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES["file"])
            name = form.cleaned_data["name"]
            desc = form.cleaned_data["description"]
            author = form.cleaned_data["author"]
            version = form.cleaned_data["version"]
            location = CONFIG.APP_DIRECTORY + request.FILES["file"].name

            anApp = App(name=name, description=desc, version=version, location=location, author=author)
            anApp.save()
            anApp.downloadLink = request.build_absolute_uri(reverse("app.views.download", kwargs={"id": anApp.id}))
            anApp.save()

            messages.add_message(request, messages.SUCCESS, "Successfully Created")
            return HttpResponseRedirect("/app/")
    else:
        form = AppForm()
    return render(request, "app/new.html", locals())
コード例 #17
0
    def serviceCounters(self):
        rules = App.getCR(App)
        counter = rules.periodCounter
        for rest in Restaurant.objects.filter(serviceStatus=True):
            counter = counter - rest.serviceCounter
        while counter > 0:
            for rest in Restaurant.objects.filter(
                    serviceStatus=True).order_by('-serviceCounter'):
                rest.serviceCounter = rest.serviceCounter + 1
                rest.save()
                counter = counter - 1
                if counter == 0:
                    break
        while counter < 0:
            for rest in Restaurant.objects.filter(
                    serviceStatus=True).order_by('serviceCounter'):
                if rest.serviceCounter > 1:
                    rest.serviceCounter = rest.serviceCounter - 1
                    rest.save()
                    counter = counter + 1
                if counter == 0:
                    break

        vehicleRestaurants = Restaurant.objects.filter(modeOfTransport=True,
                                                       serviceStatus=True,
                                                       weatherCondition=True)
        vrestCounter = 0
        for vrest in vehicleRestaurants:
            vrestCounter = vrest.serviceCounter + vrestCounter

        constantIstanbul = [
            17.5, 15.3, 13.8, 10.4, 8.1, 6.1, 4.2, 4.9, 7.4, 11.3, 13.2, 17.2
        ]
        currentDate = datetime.datetime.now()
        currentDay = currentDate.day
        totalDays = rules.periodCounter
        totalMonthsFloat = totalDays / 30
        totalMonthsRound = math.ceil(totalMonthsFloat)
        badWeatherProbability = (
            (30 - currentDay) * constantIstanbul[currentDate.month - 1]) / 30
        for i in range(1, totalMonthsRound):
            if (i - totalMonthsFloat + 1) > 0:
                badWeatherProbability = (
                    30 * (i - totalMonthsFloat) *
                    constantIstanbul[currentDate.month - 1 +
                                     i]) / 30 + badWeatherProbability
            badWeatherProbability = constantIstanbul[currentDate.month - 1 +
                                                     i] + badWeatherProbability

        if vrestCounter < int((rules.periodCounter / badWeatherProbability)):

            transporBalanceCounter = int(
                (rules.periodCounter / badWeatherProbability)) - vrestCounter
            counter = transporBalanceCounter
            while transporBalanceCounter > 0:
                for rest in Restaurant.objects.filter(
                        modeOfTransport=False,
                        serviceStatus=True,
                        weatherCondition=False).order_by('serviceCounter'):
                    rest.serviceCounter = rest.serviceCounter - 1
                    rest.save()
                    counter = counter - 1
                    if counter == 0:
                        break

                for rest in vehicleRestaurants.order_by('-serviceCounter'):
                    rest.serviceCounter = rest.serviceCounter + 1
                    rest.save()
                    transporBalanceCounter = transporBalanceCounter - 1
                    if transporBalanceCounter == 0:
                        break
コード例 #18
0
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()
        self.user = BkUser.objects.create_user('test', password='******')

        self.old_name = 'oldname'
        app = App()
        app.code = self.old_name
        app.name = self.old_name
        app.introduction = "introduction"
        app.creater = 'admin',
        app.language = 'python'
        app.auth_token = '1234'
        app.deploy_token = '1234'
        app.tags = None
        app.save()
コード例 #19
0
    def setUp(self):
        self.old_name = 'oldname'

        app = App()
        app.code = self.old_name
        app.name = self.old_name
        app.introduction = "introduction"
        app.creater = 'admin',
        app.language = 'python'
        app.auth_token = '1234'
        app.deploy_token = '1234'
        app.tags = None
        app.save()
コード例 #20
0
ファイル: tests.py プロジェクト: zzdx713/bk-PaaS
    def setUp(self):
        self.factory = RequestFactory()
        # from django.test.client import Client
        # self.client = Client()
        self.user = BkUser.objects.create_user('test', password='******')

        self.code = 'test'

        app = App()
        app.code = self.code
        app.name = self.code
        app.introduction = "introduction"
        app.creater = 'admin',
        app.language = 'python'
        app.auth_token = '1234'
        app.deploy_token = '1234'
        app.tags = None
        app.save()