コード例 #1
0
ファイル: test_models.py プロジェクト: mospina/paranuara
    def test_index_must_be_unique(self):
        Company.load_data_from_file("../../resources/companies.json")
        before_count = Company.objects.count()
        Company.load_data_from_file("../../resources/companies.json")
        after_count = Company.objects.count()

        self.assertEqual(after_count, before_count)
コード例 #2
0
ファイル: views.py プロジェクト: SarsenovZ2z/linkedin
def register(request):
    if request.method == "POST":
        try:
            user = User.objects.create_user(
                email=request.POST['email'],
                password=request.POST['password'],
            )
            user.first_name = request.POST['first_name']
            user.last_name = request.POST['last_name']
            user.save()
            profile = Profile()
            profile.user = user
            profile.save()
            is_employer = (request.POST['is_employer'] == '0')
            if (is_employer):
                company = Company()
                company.user = user
                company.save()

            return render(request, 'registration/edit.html',
                          {'is_company': is_employer})
        except:
            return render(request, 'registration/edit.html',
                          {'is_company': False})
    else:
        return render(request, 'registration/registration.html')
コード例 #3
0
def save_employee_data(request, employee_data, line_count):
    line_count = line_count + 1
    if User.objects.filter(username__iexact=employee_data['email']).exists():
        messages.error(
            request,
            f"Error! Line: {line_count} {employee_data['email']} email is taken"
        )
        return redirect('upload_employees')
    elif User.objects.filter(email__iexact=employee_data['email']).exists():
        messages.error(
            request,
            f"Error! Line: {line_count} {employee_data['email']} email is taken"
        )
        return redirect('upload_employees')
    else:
        # Store user detals
        email = employee_data['email'].lower()
        user = User.objects.create_user(first_name=employee_data['first_name'],
                                        last_name=employee_data['last_name'],
                                        username=employee_data['email'],
                                        password=employee_data['password'],
                                        email=employee_data['email'])
        user.save()
        companyObj = None
        if Company.objects.filter(name=employee_data['company']).exists():
            companyObj = Company.objects.get(name=employee_data['company'])
        else:
            companyObj = Company(name=employee_data['company'])
            companyObj.save()
        profile = Profile(user=user, company=companyObj)
        profile.save()
    return
コード例 #4
0
ファイル: views.py プロジェクト: adamrj/Companies1
def create(request):
    print(request.POST)
    company_name = request.POST.get("name")
    company_phone = request.POST.get("phone")
    company_email = request.POST.get("email")
    company_object = Company(name=company_name, phone=company_phone, email=company_email)
    company_object.save()
    return redirect("companies:index")
コード例 #5
0
def create(request):
    print(request.POST)
    company_name = request.POST.get("name")
    company_phone = request.POST.get("phone")
    company_email = request.POST.get("email")
    company_object = Company(name=company_name,
                             phone=company_phone,
                             email=company_email)
    company_object.save()
    return redirect("companies:index")
コード例 #6
0
def create_user(self, username, password, company_name):
    user = User.objects.create(username=username)
    user.set_password(password)
    user.save()
    company = Company(Name=company_name)
    company.Owned_by = user
    company.save()
    company_user = CompanyUser(User_id=user.id, Company_id=company.id)
    company_user.save()
    self.stdout.write(f'User {username} created with password {password}')
コード例 #7
0
ファイル: load_data.py プロジェクト: mospina/paranuara
    def handle(self, *args, **options):
        if not options.get("companies") or not options.get("people"):
            self.stdout.write(self.usage)
            return

        # First load companies
        for elem in options["companies"]:
            Company.load_data_from_file(elem)
        # Then load people
        for elem in options["people"]:
            load_data_from_file(elem)
コード例 #8
0
ファイル: views.py プロジェクト: mmesereau/stock_ml
def set(request):
    print("hit endpoint")
    data = app.get_companies()
    existing = Company.objects.all()
    names = []
    for existing_company in existing:
        names.append(existing_company.name)
    for item in data:
        if item[1] not in names:
            company = Company(name=item[1], ticker=item[0], industry=item[2])
            company.save()
    return HttpResponse("Success...?")
コード例 #9
0
ファイル: sync_companies.py プロジェクト: Jafte/intranet
    def handle_noargs(self, **options):
        output = options.pop("output")
        test = options.pop("test")
        if test:
            self.stdout.write(40 * ".")
            self.stdout.write("\nSync basecamp and local companies command. Ignore output..\n\n")
        if output:
            for company in Company.objects.filter(active=True).exclude(basecamp_api_key="").exclude(basecamp_id="").exclude(basecamp_base_url=""):
                username = password = company.basecamp_api_key
                base_url = company.basecamp_base_url

                bc = Basecamp(base_url, username, password)
                xml = ET.fromstring(bc.companies())

                for company in xml.findall('company'):
                    phone_number_office = company.find('phone-number-office').text
                    try:
                        client_of = company.find('client-of').text
                    except:
                        client_of = False
                    web_address = company.find('web-address').text
                    city = company.find('city').text
                    name = company.find('name').text
                    basecamp_id = company.find('id').text

                    try:
                        django_company = Company.objects.get(basecamp_id=basecamp_id)
                        self.stdout.write("Company %s already exist." % django_company)
                    except Company.DoesNotExist:
                        django_company = Company(
                            name = name,
                            basecamp_id = basecamp_id
                        )
                        django_company.save()
                        self.stdout.write("Company %s creates." % django_company)

                    if client_of:
                        try:
                            provider = Company.objects.get(basecamp_id=client_of)
                            service = Service.objects.filter(company=provider, client_company=django_company)
                            if not service:
                                service = Service(
                                    company=provider,
                                    client_company=django_company
                                )
                                service.save()
                                self.stdout.write("Service %s creates." % service)
                        except:
                            pass

        if test:
            self.stdout.write("\nFinished sync basecamp and local users command.. continuing..\n")
コード例 #10
0
ファイル: company.py プロジェクト: ktryber/aljex-sync-api
    def create_company(cls, company_data):
        updates = {}
        company_key = firebase_db.reference('companies').push().key

        company = Company(
            external_key=company_key,
            **company_data,
        )
        company.save()

        updates['companies/{key}/pk'.format(key=company_key)] = company.pk
        firebase_db.reference().update(updates)
        return company
コード例 #11
0
ファイル: views.py プロジェクト: abogdanov87/safety_work
 def post(self, request, format=None):
     company_instance = Company(
         name=request.data['name'],
         short_name=request.data['short_name'],
         inn=request.data['inn'],
         active=True,
     )
     badge = request.FILES.get('badge', None)
     if not badge is None:
         company_instance.badge = badge
     company_instance.save()
     company_instance.user.add(request.user)
     return Response(
         CompanySerializer(company_instance).data, status.HTTP_201_CREATED)
コード例 #12
0
ファイル: intersect.py プロジェクト: BluInc/YaleHack
def addtoDB(s1, s2, score):
    dcb_s1 = cb[cb.name == s1].overview
    dcb_s1 = dcb_s1[dcb_s1.index.values[0]]

    dcb_s2 = cb[cb.name == s2].overview
    dcb_s2 = dcb_s2[dcb_s2.index.values[0]]

    dal_s1 = al[al.name == s1].product_desc
    dal_s1 = dal_s1[dal_s1.index.values[0]]

    dal_s2 = al[al.name == s2].product_desc
    dal_s2 = dal_s2[dal_s2.index.values[0]]

    c1=Company(name=s1, desc_cb=dcb_s1, desc_al=dal_s1)
    c1.save()
    print(c1)
コード例 #13
0
ファイル: views.py プロジェクト: phrac/partflux
def addbuylink(request, part_id):
    p = get_object_or_404(Part, pk=part_id)
    buylinkform = BuyLinkForm(request.POST)
    if buylinkform.is_valid():
        url = buylinkform.cleaned_data['url']
        company = buylinkform.cleaned_data['company'].strip().upper()
        price = buylinkform.cleaned_data['price']
        try:
            c = Company.objects.get(slug=slugify(company))
        except ObjectDoesNotExist:
            c = Company(name=company, slug=slugify(company))
            c.save()
        buylink = BuyLink(part=p, company=c, price=price, url=url, user=request.user)
        try:
            buylink.save()
            return True
        except IntegrityError:
            return 'Link already exists'
コード例 #14
0
    def setUp(self):
        company = Company(company_name='Name')
        worker = Worker(name='Worker')
        work = Work(
            company=company,
            work_name='WorkName',
        )

        self.wp = WorkPlace(
            worker=worker,
            work=work,
            workplace_name='new workplace',
        )
コード例 #15
0
def create(request, data):
    if request.method == 'POST':
        # Collect form data.
        company_name = request.POST['company_name']
        owned_by = Staff.objects.get(user=request.user)

        # Create new Company instance.
        new_company = Company(name=company_name, owner=owned_by)
        new_company.save()

        # Add new company to workplaces.
        owned_by.workplaces.add(new_company)

        # Add owner to staff of new company.
        new_company.staff.add(owned_by)

        # Success
        data['alerts'].append(('success', 'Create successfully!',
                               'You have successfully create a new company.'))
        return redirect_with_data(request, data, '/companies/1+1/#tab2')
    else:
        return render(request, 'companies/create.html', data)
コード例 #16
0
def _fill_companies() -> None:
    company_logos_directory = Path('company_logos')
    company_names: List[str] = [
        'Workiro',
        'Rebel Rage',
        'Staffing Smarter',
        'Evilthreat',
        'Hirey',
        'SwiftAttack',
        'TROLLER',
        'Primal Assault',
    ]

    for index, companies_name in enumerate(company_names):
        owner: LaborExchangeUser
        is_created: bool

        owner, is_created = LaborExchangeUser.objects.get_or_create(
            name=f'Владелец',
            surname=f'Хозяинов_{index}',
            email=f'owner{index}@owner.ru',
            phone=f'8999777665{index}',
        )

        assert is_created, 'Admin was not created'
        owner.set_password(f'Djangotest{index}')
        owner.save()

        company_instance = Company(
            name=companies_name,
            location='Самый лучший город на Земле',
            logo=str(company_logos_directory / f'b003a3c{index + 1}.png'),
            owner=owner,
            employee_count=choice(range(1, 300)),
            description=
            'Это компания без описания, потому что её HR-специалисты — ленивые задницы',
        )
        company_instance.save()
コード例 #17
0
ファイル: script.py プロジェクト: sanchitbareja/occuhunt-web
    def handle(self, *args, **options):

        data = csv.reader(open(
            os.getcwd() + '/companies/management/commands/CCFInfo3.csv', 'rU'),
                          quotechar='"',
                          delimiter=',')
        # print (data)
        for row in data:
            # print "0"+row[0]
            new_company = Company(name=row[0],
                                  callisto_url=row[1],
                                  website=row[2],
                                  logo=row[3],
                                  expected_hires=row[4],
                                  number_employees=row[5],
                                  number_domestic_locations=row[6],
                                  number_international_locations=row[7],
                                  organization_type=row[8],
                                  company_description=row[9],
                                  job_description=row[10],
                                  position_locations=row[11],
                                  position_types=row[12])
            new_company.save()
        self.stdout.write('Success')
コード例 #18
0
    def create(self, request, *args, **kwargs):
        # get company
        company = request.data.pop('company')

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        user = serializer.instance

        # save company
        c = Company(company_name=company)
        c.generate_code()
        c.save()
        c.staff.add(user)

        return Response(serializer.data, status=status.HTTP_201_CREATED)
コード例 #19
0
ファイル: intersect.py プロジェクト: BluInc/YaleHack
def addtoDB(s1, s2, dist):
    #dcb_s1 = cb[cb.name == s1].overview
    # dcb_s1 = dcb_s1[dcb_s1.index.values[0]]

    # dcb_s2 = cb[cb.name == s2].overview
    # dcb_s2 = dcb_s2[dcb_s2.index.values[0]]


    # dal_s1 = dal_s1[dal_s1.index.values[0]]

    # dal_s2 = al[al.name == s2].product_desc
    # dal_s2 = dal_s2[dal_s2.index.values[0]]

    try:
        c1 = Company.objects.get(name=s1)
    except ObjectDoesNotExist:
        dcb_s1 = cb[cb.name == s1]
        dal_s1 = al[al.name == s1]
        c1 = Company(name=s1,
                    desc_cb=dcb_s1.overview[dcb_s1.overview.index.values[0]],
                    desc_al=dal_s1.product_desc[dal_s1.product_desc.index.values[0]],
                    cb_url=dcb_s1.crunchbase_url[dcb_s1.crunchbase_url.index.values[0]],
                    al_url=dal_s1.angellist_url[dal_s1.angellist_url.index.values[0]],
                    logo_url=dal_s1.logo_url[dal_s1.logo_url.index.values[0]],
                    company_url=dal_s1.company_url[dal_s1.company_url.index.values[0]],
                    market=dal_s1.high_concept[dal_s1.high_concept.index.values[0]])
        c1.save()

    try:
        c2 = Company.objects.get(name=s2)
    except ObjectDoesNotExist:
        dcb_s2 = cb[cb.name == s2]
        dal_s2 = al[al.name == s2]
        c2 = Company(name=s2,
                    desc_cb=dcb_s2.overview[dcb_s2.overview.index.values[0]],
                    desc_al=dal_s2.product_desc[dal_s2.product_desc.index.values[0]],
                    cb_url=dcb_s2.crunchbase_url[dcb_s2.crunchbase_url.index.values[0]],
                    al_url=dal_s2.angellist_url[dal_s2.angellist_url.index.values[0]],
                    logo_url=dal_s2.logo_url[dal_s2.logo_url.index.values[0]],
                    company_url=dal_s2.company_url[dal_s2.company_url.index.values[0]],
                    market=dal_s2.high_concept[dal_s2.high_concept.index.values[0]])
        c2.save()

    sc = Distance(score=dist, c1=c1, c2=c2)
    sc.save()
コード例 #20
0
 def handle(self, *args, **options):
     logger.info('Started updating currently listed companies')
     companies = Company.objects.filter(is_index=False)
     r = requests.get(settings.COMPANY_LIST_URL)
     records = r.json()['records']
     for record in records:
         symbol = record['securitySymbol']
         name = record['securityName']
         listing_date = record['listingDate'].split()[0]
         status = record['securityStatus']
         try:
             company = companies.get(symbol=symbol)
             companies = companies.exclude(id=company.id)
         except Company.DoesNotExist:
             company = Company(symbol=symbol)
         company.name = name
         company.is_currently_listed = True
         company.is_suspended = True if status == 'S' else False
         company.listing_date = datetime.strptime(listing_date, '%Y-%m-%d').date()
         company.save()
     companies.update(is_currently_listed=False, is_suspended=False)
     logger.info('Finished updating currently listed companies')
コード例 #21
0
    def save(self):
        self.clean()
        cleaned_data = self.cleaned_data
        userManager = MyUserManager()
        email = cleaned_data.get('email')
        firstName = cleaned_data.get('firstName')
        lastName = cleaned_data.get('lastName')
        user_type = None
        if self.is_employer_selected():
            user_type = USER_TYPE_EMPLOYER
        else:
            user_type = USER_TYPE_CANDIDATE
        password = cleaned_data.get('password')
        print(user_type)

        user = User()
        user.email = email
        user.firstName = firstName
        user.lastName = lastName
        user.user_type = user_type

        user.set_password(password)
        user.save()

        if cleaned_data.get('preferredName') != '' and cleaned_data.get(
                'preferredName') != None:
            preferredName = PreferredName()
            preferredName.user = user
            preferredName.preferredName = cleaned_data.get('preferredName')
            preferredName.save()

        if self.is_employer_selected():
            employer = Employer()
            employer.user = user

            if self.is_createCompany_selected():
                company = Company()
                company.name = cleaned_data.get('companyName')
                company.address = cleaned_data.get('address')
                company.website = cleaned_data.get('website')
                company.profile = cleaned_data.get('profile')
                company.image = cleaned_data.get('image')
                company.save()
                employer.company = company

            else:
                employer.company = get_object_or_404(
                    Company, pk=cleaned_data.get('company'))

            employer.save()
        else:
            candidate = Candidate()
            candidate.user = user
            candidate.studentID = cleaned_data.get('studentID')
            candidate.creditCompleted = cleaned_data.get('creditCompleted')
            candidate.program = cleaned_data.get('program')
            candidate.creditLeft = cleaned_data.get('creditLeft')
            candidate.gpa = cleaned_data.get('gpa')
            candidate.internationalStudent = cleaned_data.get(
                'internationalStudent')
            candidate.travel = cleaned_data.get('travel')
            candidate.timeCommitment = cleaned_data.get('timeCommitment')
            candidate.transcript = cleaned_data.get('transcript')
            candidate.save()

            for lan in self.languageFieldsNames:
                language = Language()
                language.language = cleaned_data.get(lan['language'])
                language.fluency = cleaned_data.get(lan['proficiency'])
                language.details = cleaned_data.get(lan['details'])
                language.user = user
                language.save()

        return user
コード例 #22
0
ファイル: seeds.py プロジェクト: prycey77/simpleassettracker
def create_company(name):
    C = Company(name=name)
    C.save()
    return C
コード例 #23
0
 def CreateNewEmptyCompany(cls, administrator=None):
     company = Company()
     if administrator:
         company.administrators.append(administrator.id)
     company.save()
     return company
コード例 #24
0
def register(request):
    if request.method == 'POST':
        # Retrieving all details from POST request
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        # Setting the email as the username
        username = request.POST['email']
        email = request.POST['email']
        password = request.POST['password']
        password2 = request.POST['password2']
        company_count = Company.objects.all().count()
        # Adding new company if no companies currently stored
        if company_count == 0:
            if request.POST['newCompanyInput'] == '':
                messages.error(request, 'Please enter a company name')
                return redirect('register')
            company_name = request.POST['newCompanyInput']
        else:
            # Checking if a new company was entered and storing it
            if 'newCompanyInput' in request.POST and request.POST[
                    'newCompanyInput'] != '':
                company_name = request.POST['newCompanyInput']
            else:
                company_name = request.POST['company']
        if password == password2:
            # Check username
            if ' ' in username:
                messages.error(request, 'Email cannot have spaces')
                return redirect('register')
            if User.objects.filter(username__iexact=username).exists():
                messages.error(request, 'That email is taken')
                return redirect('register')
            elif User.objects.filter(email__iexact=email).exists():
                messages.error(request, 'That email is being used')
                return redirect('register')
            else:
                # Store user detals
                email = email.lower()
                user = User.objects.create_user(first_name=first_name,
                                                last_name=last_name,
                                                username=username,
                                                password=password,
                                                email=email)
                user.save()
                if Company.objects.filter(name=company_name).exists():
                    companyObj = Company.objects.get(name=company_name)
                else:
                    companyObj = Company(name=company_name)
                    companyObj.save()
                profile = Profile(user=user, company=companyObj)
                profile.save()

                messages.success(request,
                                 'You are now registered and can login')
                return redirect('login')
        else:
            messages.error(request, 'Passwords do not match')
            return redirect('register')
    else:
        # Retrieving the list of companies to populate the dropdown during registration
        companies = Company.objects.all()
        context = {"companies": companies}
        return render(request, 'accounts/register.html', context)
コード例 #25
0
ファイル: test_models.py プロジェクト: mospina/paranuara
    def test_load_data_from_file(self):
        before_count = Company.objects.count()
        Company.load_data_from_file("../../resources/companies.json")
        after_count = Company.objects.count()

        self.assertGreater(after_count, before_count)
コード例 #26
0
ファイル: data.py プロジェクト: Foxugly/MyTaxAccountant
u = User.objects.all()
up = UserProfile(user=u[0])
up.save()

from utils.models import Country, FiscalYear
fy1 = FiscalYear(name='2015')
fy1.save()
fy2 = FiscalYear(name='2016')
fy2.save()

country1 = Country(name='Belgium')
country1.save()

from companies.models import Company
c1 = Company(name='Alpha',slug='alpha',vat_number='123456789', country=country1, active=True)
c1.save()
up.add_company(c1)
c2 = Company(name='Beta',slug='beta',vat_number='123456780', country=country1, active=True)
c2.save()
up.add_company(c2)

from years.models import Year
y11 = Year(fiscal_year=fy1, refer_company=c1, active=True)
y11.save()
c1.add_year(y11)
y12 = Year(fiscal_year=fy2, refer_company=c1, active=True)
y12.save()
c1.add_year(y12)
y21 = Year(fiscal_year=fy1, refer_company=c2, active=True)
y21.save()
コード例 #27
0
 def test_company(self):
     company = Company(company_name='Name')
     self.assertIsNotNone(company)
コード例 #28
0
def test_list_all_companies(db_session):
    repository = CompanyRepository(db_session)
    repository.save(Company(id=generate_id(), name="Pepsi"))
    result = repository.list_all()

    assert len(result) == 1
コード例 #29
0
ファイル: init.py プロジェクト: 326-queue/project
    "Systems": "orange",
    "Data": "yellow",
}
for t in colors.keys():
    industry = Industry(name=t, color=colors[t])
    industry.save()
    industries.append(industry)

print("Generating companies...")
companies = []
for i in range(10):
    company = Company(
        name=fake.company(),
        location=fake.address(),
        status=random.choice(Company.STATUSES)[0],
        size=random.choice(Company.SIZES)[0],
        donated=random.randint(0, 10000),
        updated=fake.date_time_this_month(before_now=True,
                                          after_now=False,
                                          tzinfo=None),
    )
    company.save()
    for s in random.sample(industries, random.randint(1, 3)):
        company.industries.add(s)
    company.save()
    companies.append(company)

print("Generating contacts...")
contacts = []
for i in range(20):
    contact = Contact(
        first_name=fake.first_name(),
コード例 #30
0
from companies.models import Company, Domain

companies_info = [
    {
        'schema_name': 'ford',
        'name': 'Ford',
    },
    {
        'schema_name': 'mazda',
        'name': 'Mazda',
    },
    {
        'schema_name': 'chevrolet',
        'name': 'Chevrolet',
    },
    {
        'schema_name': 'bmw',
        'name': 'BMW',
    }
]

for company in companies_info:
    company_object = Company(schema_name=company['schema_name'], name=company['name'])
    company_object.save()

    domain = Domain()
    domain.domain = '%s.localhost' % company['schema_name']
    domain.tenant = company_object
    domain.is_primary = True
    domain.save()
コード例 #31
0
from companies.models import Company, Domain

# create your public tenant
tenant = Company(schema_name='public',
                name='Colombia Cars')
tenant.save()

# Add one or more domains for the tenant
domain = Domain()
domain.domain = 'localhost'
domain.tenant = tenant
domain.is_primary = True
domain.save()
コード例 #32
0
 def test_creating_new_company_and_saving_it_to_the_database(self):
     # Test creating a new event object.
     category = Category.objects.create(name="Software", slug="software")
     #user = User.objects.create(username="******")
     country = Country.objects.create(name="America")
     company = Company()
     company.name ="Stance Data"
     company.slug = "stance-data"
     company.logo = "" #ImageField(blank=True, null=True, storage=gs, upload_to="images/companies_imgs/")
     company.overview = ""
     company.value_proposition = ""
     company.description = ""
     company.company_status = 2 #= IntegerField(choices=COMPANY_STATUS_CHOICES, blank=True, null=True)
     company.employee_quantity = 2 #IntegerField(choices=EMPLOYEE_QUANTITY_CHOICES, blank=True, null=True)
     company.main_phone = ""
     company.email = "*****@*****.**"
     company.industries = ""
     company.technologies = ""
     company.categories = category #ForeignKey(Category, related_name="Categories", null=True, blank=True)
     company.applications =""
     company.tags = ""
     company.country = country
     company.product = ""
     company.contact = ""
     # Testing __unicode__ method
     self.assertEquals(unicode(company.name), 'Stance Data')
コード例 #33
0
 def handle(self, *args, **options):
     for filename in options["filenames"]:
         Company.load_data_from_file(filename)
コード例 #34
0
# Created by Adam Jacobs, June 2017

from django.contrib.auth.models import User
from exhibitors import models
from orders.models import Order, Product, ProductType
from fair.models import Fair
from companies.models import Company, Contact
from datetime import date

# Get super user
u = User.objects.get()

fair = Fair(name="fair1", year=2017, description="description", current=True )
fair.save()

company = Company(name="TestCompany", organisation_type='company')
company.save()

contact = Contact(user=u, belongs_to=company, name="contact name", email="*****@*****.**", active=True, confirmed=True)
contact.save()

banquetType = ProductType(name="Banquet", description="...")
banquetType.save()
lunchType = ProductType(name="AdditionalLunch", description="...")
lunchType.save()
eventsType = ProductType(name="Events", description="...")
eventsType.save()
roomsType = ProductType(name="Rooms", description="...")
roomsType.save()
novaType = ProductType(name="Nova", description="...")
novaType.save()
コード例 #35
0
def main_parse(search,
               page,
               quantity,
               vacancy_on_page=10,
               location=None,
               country=None):
    country_site = IndeedCountrySites.objects.get(code_iso=country)
    start_at = page * vacancy_on_page

    debug_log(f'{"#"* 21}\nParse starts at: {start_at}')

    total_company_add = 0
    total_vacancies_add = 0

    for start in range(start_at, quantity, vacancy_on_page):

        page_num = int(start / vacancy_on_page)
        debug_log(f"Parse Page: {page_num}")

        params = {'start': start, 'sort': settings.DEFAULT_SORT}
        if search:
            params.update({'q': search})
        if location:
            params.update({'l': location})

        debug_log(f'Params: {params}')

        try:
            vacancies = get_vacancies_on_page(country=country,
                                              session=session,
                                              params=params)
            if vacancies is None:
                continue

            company_add = 0
            vacancies_add = 0

            for vacancy_data in vacancies:

                company_uid = vacancy_data.get('cmpid', None)
                company_link = vacancy_data.get('company_link', None)

                if company_uid:
                    company = Company.objects.filter(uid=company_uid).first()
                    if not company and company_link:
                        _counry = IndeedCountrySites.objects.get(
                            code_iso=country)
                        company_link = normalize_url(_counry.site,
                                                     company_link)
                        company_data = get_company_info(session, company_link)
                        if company_data:
                            company = Company(
                                uid=company_uid,
                                name=company_data.get('title'),
                                link=company_link,
                                about=company_data.get('about'),
                                headquarters=company_data.get('headquarters'),
                                employees=company_data.get('employees'),
                                industry=company_data.get('industry'),
                                website=company_data.get('website'),
                                revenue=company_data.get('revenue'),
                                country_site=country_site)

                            company.save()

                            company_add += 1
                        else:
                            company = None
                else:
                    company = None

                job_key = vacancy_data.get('jk')
                if not job_key:
                    continue

                exist_vacancy = Vacancy.objects.filter(job_key=job_key).first()
                print(exist_vacancy)

                if exist_vacancy:
                    continue

                vacancy_url = vacancy_data.get('link')

                vacancy = Vacancy(
                    job_key=job_key,
                    title=vacancy_data.get('title'),
                    link=normalize_url(country_site.site, vacancy_url),
                    description_text=vacancy_data.get('description',
                                                      {}).get('text'),
                    description_html=vacancy_data.get('description',
                                                      {}).get('html'),
                    location=vacancy_data.get('loc'),
                    location_uid=vacancy_data.get('locid'),
                    country=vacancy_data.get('country'),
                    city=vacancy_data.get('city'),
                    zip=vacancy_data.get('zip'),
                    company_name=url_parse.unquote(
                        vacancy_data.get('srcname', '')),
                    company_uid=vacancy_data.get('cmpid'),
                    company_link=normalize_url(country_site.site, company_link)
                    if company_link else None,
                    company_id=company.id if company else None,
                    raw_data=vacancy_data,
                    country_site=country_site)
                _data = {
                    'title': vacancy.title,
                    'link': vacancy.link,
                    'description_text': vacancy.description_text,
                    'description_html': vacancy.description_html,
                    'location': vacancy.location,
                    'location_uid': vacancy.location_uid,
                    'country': vacancy.company,
                    'city': vacancy.city,
                    'zip': vacancy.zip,
                    'company_name': vacancy.company_name,
                    'company_uid': vacancy.company_uid,
                    'company_link': vacancy.company_link,
                    'company_id': company.id if company else None,
                    'raw_data': vacancy.raw_data,
                    'country_site': country_site
                }
                Vacancy.objects.get_or_create(job_key=job_key, defaults=_data)
                vacancies_add += 1

            total_company_add += company_add
            total_vacancies_add += vacancies_add
            debug_log(
                f"TC: {total_company_add}, TV: {total_vacancies_add}, C: {company_add}, V: {vacancies_add}"
            )

        except Exception as e:
            tb = traceback.format_exc()
            error_log(f"###\nPage {page}\n{tb}")
            raise