本文整理汇总了Python中jobs.models.Job.save方法的典型用法代码示例。如果您正苦于以下问题:Python Job.save方法的具体用法?Python Job.save怎么用?Python Job.save使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jobs.models.Job
的用法示例。
在下文中一共展示了Job.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
def run(job, *args, **kwargs):
try:
servers = job.server_set.all()
for server in servers:
job.set_progress("Checking server {} for snapshots...".format(server))
snapshots = ServerSnapshot.objects.filter(server_id=server.id)
if not snapshots:
job.set_progress('No snapshots exist for server {}'.format(server))
continue
logger.info("Found snapshot, noting for deletion...")
job_params = DeleteSnapshotsParameters.objects.create()
job_params.snapshots.add(*snapshots)
logger.info("Creating job...")
child_job = Job(
type="delete_snapshots",
job_parameters=job_params,
owner=job.owner,
parent_job=job,
)
child_job.save()
child_job.server_set.add(server)
msg = (' Job #{} has been created to delete {} snapshot{} from server '
'{}.').format(
child_job.pk, len(snapshots),
's' if len(snapshots) > 1 else '', server)
job.set_progress(msg)
job.set_progress('Finished looking for snapshots on servers. Check child' +
' job(s) for progress updates.')
except Exception as err:
return ('FAILURE', '', err)
return ('', '', '')
示例2: handle
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
def handle(self, *args, **options):
listings = self.get_for_page(1)
jobs = Job.objects.all()
for job in jobs:
job.delete()
for listing in listings:
try:
location = listing['company']['location']['city']
except:
location = ''
try:
company = str(listing['company']['name'])
except:
company = ''
newjob = Job(title=listing['title'],
company=company,
location=location,
url=listing['url'],
data=json.dumps(listing),
created=listing['post_date'])
newjob.save()
示例3: post
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
def post(self, request):
json_data = json.loads(request.body)
company = Company.objects.get(user=request.user)
job = Job(**json_data)
job.company = company
job.user = request.user
job.save()
return JsonResponse({"status": "ok", "id": job.id, 'msg': ''})
示例4: test_get_nonexistant_job_product
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
def test_get_nonexistant_job_product(self):
# make a deleted job:
job = Job(job_name="counter")
job.save()
job_key = job.key()
job.delete()
response = self.client.get(reverse('jobs.product', args=(job_key,)))
self.assertEqual(response.status_code, 404)
示例5: create_file_job
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
def create_file_job(name, sf_id, *args, **kwargs):
"""MD5, backup, etc"""
jobargs = [sf_id] + list(args)
job = Job(funcname=name, jobtype=jobmap[name]['type'],
timestamp=timezone.now(),
state=Jobstates.PENDING, args=json.dumps(jobargs),
kwargs=json.dumps(kwargs))
job.save()
FileJob.objects.create(storedfile_id=sf_id, job_id=job.id)
return job
示例6: store_ds_job
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
def store_ds_job(name, prejob_args, **kwargs):
pjres = jobmap[name]['getfns'](*prejob_args)
sf_ids = [x.id for x in pjres]
jobargs = prejob_args + sf_ids
job = Job(funcname=name, jobtype=jobmap[name]['type'],
timestamp=timezone.now(),
state=Jobstates.PENDING, args=json.dumps(jobargs),
kwargs=json.dumps(kwargs))
job.save()
FileJob.objects.bulk_create([FileJob(storedfile_id=sf_id, job_id=job.id) for sf_id in sf_ids])
return job
示例7: test_job_reaper_kills_old_jobs
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
def test_job_reaper_kills_old_jobs(self):
# make an old job:
job = Job(job_name='counter')
job.started = datetime.datetime.now() - timedelta(days=3)
job.save()
old_job_key = job.key()
response = self.client.post(reverse('jobs.start'), {
'job_name': 'counter'
})
json_response = simplejson.loads(response.content)
self.assert_json_success(json_response)
self.assertEqual(Job.get(old_job_key), None)
示例8: test_saving_and_retrieving_jobs
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
def test_saving_and_retrieving_jobs(self):
first_job = Job()
first_job.name = 'first_job_ever'
first_job.save()
second_job = Job()
second_job.name = 'job_number_two'
second_job.save()
saved_jobs = Job.objects.all()
self.assertEqual(saved_jobs.count(), 2)
first_saved_job = saved_jobs[0]
second_saved_job = saved_jobs[1]
self.assertEqual(first_saved_job.name, 'first_job_ever')
self.assertEqual(second_saved_job.name, 'job_number_two')
示例9: obj_update
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
def obj_update(self, bundle, **kwargs):
"""
Update to deactive mostly
"""
try:
if 'deactivate' in bundle.data.keys() and bundle.data['deactivate']:
existing_job = Job.objects.get(id=bundle.data['job_id'])
existing_job.deactivate = True
existing_job.save()
bundle.obj = existing_job
else:
company = Company.objects.get(id=bundle.data['company_id'])
new_job = Job(name=bundle.data['name'], job_type=bundle.data['job_type'], location=bundle.data['location'], description=bundle.data['description'], company=company)
new_job.save()
bundle.obj = new_job
except Exception, e:
print e
raise e
示例10: JobModelTest
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
class JobModelTest(TestCase):
def setUp(self):
self.job = Job()
self.job.audit = AuditFactory()
self.job.user = UserFactory()
def test_jobs_can_be_created(self):
self.job.full_clean() # Should not raise
self.job.save() # Should not raise
def test_job_initial_state(self):
"Job initial state should be RECEIVED"
self.assertEqual(self.job.state, Job.RECEIVED_STATE)
def test_job_creation_timestamp(self):
start = timezone.now()
job = JobFactory()
end = timezone.now()
self.assertLessEqual(start, job.created_at)
self.assertLessEqual(job.created_at, end)
def test_job_report_url(self):
"Fresh and unfinished jobs have no report file"
job = JobFactory()
with self.assertRaises(ValueError):
job.report_file.url
@patch('django.core.files.storage.default_storage._wrapped')
def test_finished_job_report_url(self, storage_mock):
file_mock = MagicMock(spec=File, name='FileMock')
file_mock.name = 'test_file.txt'
storage_mock.url = MagicMock('url')
storage_mock.url.return_value = file_mock.name
storage_mock.save.return_value = file_mock
self.job.add_report(file_mock)
self.assertEqual(self.job.report_file, file_mock)
self.assertEqual(self.job.state, Job.SUCCESS_STATE)
示例11: obj_create
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
def obj_create(self, bundle, **kwargs):
"""
Create or delete a new job
"""
print 1
try:
if 'deactivate' in bundle.data.keys() and bundle.data['deactivate']:
print 2
existing_job = Job.objects.get(id=bundle.data['job_id'])
existing_job.deactivate = True
existing_job.save()
bundle.obj = existing_job
else:
print 3
company = Company.objects.get(id=bundle.data['company_id'])
new_job = Job(name=bundle.data['name'], job_type=bundle.data['job_type'], location=bundle.data['location'], description=bundle.data['description'], company=company)
new_job.save()
bundle.obj = new_job
except Exception, e:
print e
raise e
示例12: publish
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
def publish(self, request, pk=None):
"""
use for draft job publish
"""
draft_job = self.get_object()
serializer = ActionSerializer(data=request.data)
if serializer.is_valid():
if serializer.data.pop('action') == AVAILABLE_ACTIONS['JOB_PUBLISH']:
now = datetime.now().strftime('%Y%m%d%H%M%S%f') + '%s' % pk
job_to_publish = Job()
job_to_publish.owner = draft_job.owner
job_to_publish.time_of_publish = timezone.now()
job_to_publish.job_id = now
job_to_publish.job_list_type = draft_job.job_list_type
job_to_publish.status = Job.STATUS.active
job_to_publish.job_rate = draft_job.job_rate
job_to_publish.promotion_banner = draft_job.promotion_banner
job_to_publish.title = draft_job.title
job_to_publish.detail = draft_job.detail
job_to_publish.time_of_release = draft_job.time_of_release
job_to_publish.short_description = draft_job.short_description
# if job_to_publish.support_image.all():
# for image in draft_job.support_image:
# SupportImage.objects.create(job=draft_job, image=image.image)
support_image = SupportImage.objects.get(pk=draft_job.support_image.pk)
support_image.pk = None
support_image.save()
job_to_publish.support_image = support_image
job_to_publish.postal_code = draft_job.postal_code
job_to_publish.keywords = draft_job.keywords
job_to_publish.multiple_job_rates = draft_job.multiple_job_rates
job_to_publish.save()
return Response({'status': 'job published'})
else:
return Response({'status': 'action not supported'})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
示例13: create
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
def create(request, create_form=CreateJobForm,
template_name='jobs/create_form.html', success_url=None,
extra_context=None):
#profile = Profile.objects.get(user_id=request.user.id)
#if profile and not(profile.if_employer):
# return render_to_response('jobs/index.html', {'form': form}, context_instance=RequestContext(request))
form = create_form()
if request.method == 'POST':
form = create_form(request.POST, request.FILES)
if form.is_valid():
job = Job()
job.user = request.user
job.name = form.cleaned_data['name']
job.location = form.cleaned_data['location']
job.intern_project = form.cleaned_data['intern_project']
job.save()
# split by new line
names_values = form.cleaned_data['names_values'].split('\n')
# go trough all names and values
for name_value in names_values:
# skip extra spaces and split by first colon
result = ' '.join(name_value.split()).split(":", 1)
# when name and value
if len(result) == 2:
parameter = JobParameter()
parameter.name = result[0].strip()
parameter.value = result[1].strip()
parameter.container = job
parameter.save()
return redirect('/jobs')
return render_to_response('jobs/create_form.html', {'form': form}, context_instance=RequestContext(request))
示例14: TestJob
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
class TestJob(TestCase):
def setUp(self):
self.client = Client()
self.job = Job()
self.job.position = "test"
self.job.company_name = "company test"
self.job.website = "pythonjobs.ie"
self.job.category = "full"
self.job.description = "Testing"
self.job.email = "[email protected]"
self.job.location = "Testing"
self.job.save()
def testDown(self):
Job.objects.all().delete()
def test_index_returns_200(self):
response = self.client.get(reverse("job-home"))
self.assertEquals(response.status_code, 200)
def test_index_template(self):
response = self.client.get("/")
self.assertTemplateUsed(response, "index.html")
def test_index_list_active_jobs(self):
job = mommy.make(Job, status=0)
response = self.client.get(reverse("job-home"))
self.assertEquals(len(response.context["jobs"]), 1)
def test_show_returns_200(self):
response = self.client.get(reverse("job-show", args=[self.job.pk]))
self.assertEquals(response.status_code, 200)
def test_show_template(self):
response = self.client.get(reverse("job-show", args=[self.job.pk]))
self.assertTemplateUsed(response, "show.html")
def test_new_returns_200(self):
response = self.client.get(reverse("job-new"))
self.assertEquals(response.status_code, 200)
def test_new_template(self):
response = self.client.get(reverse("job-new"))
self.assertTemplateUsed(response, "new.html")
def test_create_new_job(self):
self.job.pk = 0
params = model_to_dict(self.job)
response = self.client.post(reverse("job-new"), params)
self.assertEquals(response.status_code, 302)
def test_edit_returns_200(self):
response = self.client.get(reverse("job-edit", args=[self.job.token]))
self.assertEquals(response.status_code, 200)
def test_edit_template(self):
response = self.client.get(reverse("job-edit", args=[self.job.token]))
self.assertTemplateUsed(response, "edit.html")
def test_feed_items_returns_not_empty_list(self):
self.assertNotEqual(len(JobsFeed.items(self)), 0)
def test_feed_title_returns_job_position(self):
item = self.job
self.assertEquals(JobsFeed.item_title(self, item), item.position)
def test_feed_description_returns_job_description(self):
feed_description = JobsFeed.item_description(self, self.job)
self.assertEquals(feed_description, self.job.description)
def test_feed_author_name_returns_job_pythonjobs_ie(self):
feed_author = JobsFeed.item_author_name(self, self.job)
self.assertEquals(feed_author, 'pythonjobs.ie')
def test_feed_pubdate_returns_job_created_at(self):
feed_pubdate = JobsFeed.item_pubdate(self, self.job)
self.assertEquals(feed_pubdate, self.job.created_at)
def test_feed_link_returns_job_link(self):
job_link = reverse('job-show', args=[self.job.pk])
self.assertEquals(JobsFeed.item_link(self, self.job), job_link)
示例15: TestJob
# 需要导入模块: from jobs.models import Job [as 别名]
# 或者: from jobs.models.Job import save [as 别名]
class TestJob(TestCase):
"""
Test cases for Job model
"""
def setUp(self,):
self.path = os.path.dirname(os.path.realpath(__file__))
self.formats = ExportFormat.objects.all() #pre-loaded by 'insert_export_formats' migration
Group.objects.create(name='TestDefaultExportExtentGroup')
self.user = User.objects.create(username='demo', email='[email protected]', password='demo')
bbox = Polygon.from_bbox((-7.96, 22.6, -8.14, 27.12))
the_geom = GEOSGeometry(bbox, srid=4326)
self.job = Job(name='TestJob',
description='Test description', event='Nepal activation',
user=self.user, the_geom=the_geom)
self.job.save()
self.uid = self.job.uid
# add the formats to the job
self.job.formats = self.formats
self.job.save()
self.tags = [('building','yes'), ('place','city'), ('highway','service'), ('aeroway','helipad')]
for tag in self.tags:
tag = Tag.objects.create(
key = tag[0],
value = tag[1],
job = self.job
)
def test_job_creation(self,):
saved_job = Job.objects.all()[0]
self.assertEqual(self.job, saved_job)
self.assertEquals(self.uid, saved_job.uid)
self.assertIsNotNone(saved_job.created_at)
self.assertIsNotNone(saved_job.updated_at)
saved_formats = saved_job.formats.all()
self.assertIsNotNone(saved_formats)
self.assertItemsEqual(saved_formats, self.formats)
tags = saved_job.tags.all()
self.assertEquals(4, len(tags))
self.assertEquals('Test description', saved_job.description)
self.assertEquals(0, saved_job.configs.all().count())
def test_job_creation_with_config(self,):
saved_job = Job.objects.all()[0]
self.assertEqual(self.job, saved_job)
self.assertEquals(self.uid, saved_job.uid)
self.assertIsNotNone(saved_job.created_at)
self.assertIsNotNone(saved_job.updated_at)
saved_formats = saved_job.formats.all()
self.assertIsNotNone(saved_formats)
self.assertItemsEqual(saved_formats, self.formats)
# attach a configuration to a job
f = File(open(self.path + '/files/hdm_presets.xml'))
filename = f.name.split('/')[-1]
config = ExportConfig.objects.create(name='Test Preset Config', filename=filename,
upload=f, config_type='PRESET', user=self.user)
f.close()
self.assertIsNotNone(config)
uid = config.uid
saved_job.configs.add(config)
saved_config = saved_job.configs.all()[0]
self.assertEqual(config, saved_config)
saved_config.delete() #cleanup
def test_spatial_fields(self,):
bbox = Polygon.from_bbox((-7.96, 22.6, -8.14, 27.12)) # in africa
the_geom = GEOSGeometry(bbox, srid=4326)
the_geog = GEOSGeometry(bbox)
the_geom_webmercator = the_geom.transform(ct=3857, clone=True)
job = Job.objects.all()[0]
self.assertIsNotNone(job)
geom = job.the_geom
geog = job.the_geog
geom_web = job.the_geom_webmercator
self.assertEqual(the_geom, geom)
self.assertEqual(the_geog, geog)
self.assertEqual(the_geom_webmercator, geom_web)
def test_fields(self, ):
job = Job.objects.all()[0]
self.assertEquals('TestJob', job.name)
self.assertEquals('Test description', job.description)
self.assertEquals('Nepal activation', job.event)
self.assertEqual(self.user, job.user)
def test_str(self, ):
job = Job.objects.all()[0]
self.assertEquals(str(job), 'TestJob')
def test_job_region(self, ):
bbox = Polygon.from_bbox((-7.96, 22.6, -8.14, 27.12)) # africa
region = Region.objects.filter(the_geom__contains=bbox)[0]
self.assertIsNotNone(region)
self.assertEquals('Africa', region.name)
self.job.region = region
self.job.save()
saved_job = Job.objects.all()[0]
self.assertEqual(saved_job.region, region)
def test_overpass_extents(self,):
job = Job.objects.all()[0]
#.........这里部分代码省略.........