I have tried to call the two method inside the function where I couldn't able to call those method. I have tried few approaches but not succeeded. Here, What I have tried
"UserStartShift", "UserStopShift" are the API functions which have GET and POST method in it. These API are working fine individually, I wanted to return a different response using the conditional statement.
views.py:
# startshift
#api_view(['GET'])
def UserStartShift(request):
if request.method == 'POST':
UserId = request.data.get('UserId')
Ip = request.data.get('Ip')
PortNumber = request.data.get('PortNumber')
print("UserId-->", UserId)
print("Ip-->", Ip)
print('Portnumber-->', PortNumber)
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[Usp_StartShift] #UserId=%s, #IP=%s, #Port=%s', (UserId, Ip, PortNumber,))
return Response(True, status=status.HTTP_200_OK)
# endshift
#api_view(['GET'])
def UserStopShift(request, UserId):
try:
users = tblUserShiftDetails.objects.filter(UserId=UserId)
except tblUserShiftDetails.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[USP_StopShift] #UserId=%s',(UserId,))
return Response(True)
#UserShiftDetailsView
#api_view(['GET'])
def UserShiftDetailsView(request, userid):
try:
users = tblUserShiftDetails.objects.filter(UserId=userid)
except tblUserShiftDetails.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
if UserStartShift == True:
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[USP_GetCurrentShiftDetails] #UserId=%s',(userid,))
result_set = cursor.fetchall()
for row in result_set:
row = row[0]
return Response({"IsStarted":True,"EstimatedShifEnd":(row + datetime.timedelta(hours=9)).strftime('%d-%m-%Y %H:%M %p'),"ReasonforAccess": "null"})
elif UserStopShift == True :
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[USP_GetCurrentShiftDetails] #UserId=%s',(userid,))
result_set = cursor.fetchall()
for row in result_set:
row = row[0]
return Response({"IsStarted":False,"EstimatedShifEnd":"null","ReasonforAccess": "null"})
Related
I tried calling the another function inside the function which will return the response.I have tried this approach but couldn't able to achieve it.
I'm just getting error as
AssertionError at /api/Data/CurrentRunningActivity2/54
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
views.py:
#api_view(['GET'])
def CurrentRunningActivityView2(request, UserID):
if request.method == 'GET':
CurrentRunningActivity(UserID)
def CurrentRunningActivity(UserID):
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivity] #UserId=%s',(UserID,))
result_set = cursor.fetchall()
for row in result_set:
TaskId=row[0]
Number=row[1]
Opened=row[2]
Contacttype=row[3]
Category1=row[4]
State=row[5]
Assignmentgroup=row[6]
CountryLocation=row[7]
Openedfor=row[8]
Employeenumber=row[9]
Shortdescription=row[10]
Internaldescription=row[11]
Additionalcomments=row[12]
TaskName = row[1]
print("Number", Number)
return Response({ "TaskId": TaskId, "Number":Number,"Opened":Opened, "Contacttype":Contacttype,
"Category1":Category1, "State":State, "Assignmentgroup":Assignmentgroup, "CountryLocation":CountryLocation,
"Openedfor":Openedfor, "Employeenumber":Employeenumber , "Shortdescription":Shortdescription,
"Internaldescription":Internaldescription, "Additionalcomments":Additionalcomments,"TaskName":TaskName},status=status.HTTP_200_OK)
Put return statement in the CurrentRunningActivityView2 to return the Response from CurrentRunningActivity. Otherwise it won't return the Response from the second function.
#api_view(['GET'])
def CurrentRunningActivityView2(request, UserID):
if request.method == 'GET':
return CurrentRunningActivity(UserID)
I wanted to access the value of the function outside in Django rest framework. I have checked this function which return value but I want to call that return value in another function.
I have tried this approach where I'm getting output ticketid as 'None'
views.py:
def GetUserTaskId(request):
userid = request.data.get('UserId')
ReportId = request.data.get('ReportId')
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[USP_GetUserTaskId] #UserId=%s, #Ticket=%s', (userid, ReportId))
result_set =cursor.fetchall()
for row in result_set:
TaskId=row[0]
return Response({"TaskId":TaskId})
def inserttask(request):
ticketId = GetUserTaskId(request)
print("ticketId--->",ticketId)
if ticketId is not None:
/***somecode***/
Why not do something like this?
# common.py
def get_task_id(user_id, report_id):
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[USP_GetUserTaskId] #UserId=%s, #Ticket=%s', (user_id, report_id))
result_set = cursor.fetchall()
for row in result_set:
TaskId=row[0]
return TaskId
# views.py
from .common import get_task_id
def GetUserTaskId(request):
userid = request.data.get('UserId')
ReportId = request.data.get('ReportId')
task_id = get_task_id(userid, ReportId) # call our function
return Response({"TaskId": task_id})
def inserttask(request):
userid = request.data.get('UserId')
ReportId = request.data.get('ReportId')
ticketId = get_task_id(userid, ReportId) # call our function
print("ticketId--->",ticketId)
if ticketId is not None:
pass
# somecode
I have a django app that contains samples. On my home page, it displays a table with many samples, containing hyperlinks to the 'Sample page' - which is a view get request.
When I click on several of these samples in tandem, to open new tabs, each to a specific tab - I am getting cross over of data - I.e the url sample_id kwargs is different, but the page is displaying the same results which is incorrect. When i refresh the page, the correct sample data appears.
Is there any way around this happening is a user is to open several different sample tabs at the same time? This would impact on results and could cause errors in the workflow offered by the django app.
*is this because my view is processing too much, so the different view request=s ends up over lapping ?
Edit: adding view:
class FilterVariantSampleView(ReportView, ReportPDFGenerator, FileGenerator, limsQuery):
template_name = os.path.join(
'results',
'filter_templates',
'sample_page.html'
)
type = 'sample'
choice = False
group_required = ['filter']
def get(self, request, *args, **kwargs):
self.user = request.user
self.obtain_sample_information(kwargs)
self.obtain_patient_information()
self.obtain_header()
# create sample notes form
sample_notes_form = SampleNotesForm(
instance=self.sample_obj)
self.context['sample_notes_form'] = sample_notes_form
self.create_variant_filter_formset()
panel_list = [o.run_id.machine_panel_id.panel_id
for o in self.all_sr_obj]
if len(panel_list):
self.panel_obj = panel_list[0]
# self.generate_hotspot_form()
self.assess_fails()
crs_qs = ClinicallyReportedSample.objects.filter(
sample_id=self.sample_obj)
crs_qs = crs_qs.exclude(
reported_on_panel__parent_panel__isnull=False,
primary_technical_report=False,
final_technical_report=False
)
remove_report_form_list = []
lims_molecular_results = self.query_lims_clone_molecular(
qs=crs_qs)
mol_df = lims_molecular_results[0]
summary = lims_molecular_results[1]
self.context['summary'] = summary
if crs_qs.count() == 1:
crs_obj = crs_qs[0]
self.context['crs_qs'] = crs_qs
remove_report_form = RemoveDiagnosticReportForm(
instance=crs_obj)
remove_report_form_list.append(remove_report_form)
else:
messages.add_message(self.request, messages.WARNING,
'This sample has been sequenced on multiple panels.')
self.context['crs_qs'] = crs_qs
lims_molecular_results = self.query_molecular_lims(
sample_obj=self.sample_obj)
for crs_obj in crs_qs:
remove_report_form = RemoveDiagnosticReportForm(
instance=crs_obj)
remove_report_form_list.append(remove_report_form)
if crs_obj.diagnostic_report_required == False:
messages.add_message(self.request, messages.WARNING,
f'This sample does NOT require a diagnostic reoprt '
f'for the {crs_obj.reported_on_panel} panel.')
self.context['remove_report_form_list'] = remove_report_form_list
return render(request, self.template_name, self.context)
def post(self, request, *args, **kwargs):
"""
"""
self.define_variant_filter_formset()
submit = request.POST.get('submit', None)
if submit:
if submit == 'Modify sample':
logger.info('')
logger.info('Sample: {}'.format(self.sample_obj))
logger.info("Submit: '{}'".format(submit))
# pass POST dict to formset
modify_formset = self.CRVFormSet(request.POST, prefix='crv')
# validate
if modify_formset.is_valid():
logger.info('Modify Variant Formset valid')
logger.info('')
self.modify_variants(modify_formset)
self.modify_sample()
return HttpResponseRedirect(
reverse('results:filter_variant_sample',
kwargs={'sample_id': self.sample_obj.id}))
else:
msg = ('Modify ClinicallyReportedVariant '
f'Formset NOT valid: {modify_formset.errors}')
logger.error(msg)
messages.add_message(request, messages.ERROR, msg)
return HttpResponseRedirect(
reverse('results:filter_variant_sample',
kwargs={'sample_id': self.sample_obj.id}))
elif submit == 'Update':
form = RemoveDiagnosticReportForm(request.POST,
instance=ClinicallyReportedSample.objects.get(
sample_id=kwargs['sample_id'],
reported_on_panel=request.POST['reported_on_panel'])
)
if form.is_valid():
logger.info('RemoveDiagnosticReportForm is valid')
try:
form.save()
except Exception as e:
logger.error(e)
else:
msg = f'RemoveDiagnosticReportForm is NOT valid: {form.errors}'
logger.error(msg)
messages.add_message(self.request, messages.ERROR, msg)
return HttpResponseRedirect(request.path_info)
elif 'Download' in submit:
panel_name = submit.split(' ')[1]
self.panel_obj = Panel.objects.get(panel_name=panel_name)
self.crs_obj = ClinicallyReportedSample.objects.get(
sample_id=self.sample_obj, reported_on_panel=self.panel_obj)
if 'panel data' in submit:
logger.info(f'Downloading data for {self.sample_obj}')
if self.crs_obj.sample_id.external_dept.site in ['Newcastle', 'Sheffield']:
downloaded_data = self.download_yne_data()
if downloaded_data:
self.crs_obj.downloaded_data = True
self.crs_obj.downloaded_data_user = request.user
self.crs_obj.downloaded_data_date = timezone.now()
self.crs_obj.save()
return downloaded_data
else:
return HttpResponseRedirect(self.request.path_info)
elif 'report' in submit:
logger.info(f'Downloading report for {self.sample_obj}')
# update crs_obj
self.crs_obj.download_technical_report = True
self.crs_obj.download_technical_report_user = self.user
self.crs_obj.download_technical_report_date = timezone.now()
self.crs_obj.save()
# return HttpResponseRedirect(self.request.path_info)
lims_molecular_results = self.query_molecular_lims(
sample_obj=self.sample_obj)
mol_df = lims_molecular_results[0]
summary = lims_molecular_results[1]
if mol_df.empty:
logger.info('No molecular tests done')
self.latex_context['gene_status'] = False
else:
gene = mol_df[
(mol_df['test_name'] == 'gene') &
(mol_df['status'] == 'complete')
]
if gene.empty:
self.context['gene'] = False
else:
msg = ("gene Sanger in-fill test has been completed.{}")
result = gene['result'].to_string(index=False)
if result == 'normal or wild-type':
msg = msg.format(' No detectable variants.')
msg_info = messages.INFO
gene_df = pd.DataFrame()
elif result == 'failed':
msg = msg.format(' Unfortunately the test failed.')
msg_info = messages.WARNING
gene_df = pd.DataFrame()
elif result == 'mutated' or result == 'suspicious':
gene_df = self.get_gene_result(gene, technical_report=True)
if result == 'suspicious':
msg = msg.format(' There is suspicion of a variant '
'(see below for more information).')
else:
msg = msg.format(' A variant was detected '
'(see below for more information).')
msg_info = messages.INFO
else:
msg = msg.format(' Error - contact administrator.')
msg_info = messages.ERROR
result = 'error'
gene_df = pd.DataFrame()
self.latex_context['gene_status'] = result
self.latex_context['gene_df'] = gene_df
logger.info(msg)
messages.add_message(self.request, msg_info, msg)
print(self.latex_context)
# call method from TechnicalReportPDFGenerator
self.generateReport(report_type='technical')
response = self.download_technical_report()
return response
return render(request, self.template_name, self.context)
This may be due to the cache of your browser, are you sure the calls are going through the first time ?
I try to create a counter inside session but I fail. the session is print out the result I added once and it doesn't increment the process when I want to add a new comment again. the comment will be added but counter is still equal to one so, how can I do increment into session:
def post(self, request, user_slug, *args, **kwargs):
my_question = UserAsking.objects.get(ask_slug=user_slug)
userprof = UserProfile.objects.get(userasking__ask_slug=user_slug)
comment_form = CommentForm(request.POST, instance=request.user)
name = "%s %s" % (self.request.user.first_name, self.request.user.last_name)
username = self.request.user.username
logo = self.request.user.userprofile.logo.url
if comment_form.is_valid():
comment_request = self.request.POST.get('comment', None)
comment_form = Comment.objects.create(comment=comment_request,
userasking_id=my_question.id,
userprofile_id=userprof.id,
name=name,
username=username,
logo=logo,
comment_slug=my_question.ask_slug
)
q = UserAsking.objects.get(ask_slug=my_question.ask_slug)
c = comment_form
u = comment_form.userprofile
if 'notify_counts' in request.session:
counter = request.session.get('notify_counts', 0)
request.session['notify_counts'] = counter + 1
request.session.save()
print('%s is commented your post: %s and comment is (%s) notify = %i'
%(u, q, c, counter))
return redirect('community:question_view', user_slug)
# return redirect('community:question_view', comment_form.userasking.ask_slug)
return render(request, 'community/question_view.html', {'comment_form': comment_form})
Django automatically saves to the session database when the session has been modified, so you won't bother to save it manually, take a look:when session are stored[Django-Doc].
def post(request,...):
...
notify_counts = request.session.get('notify_counts')
if notify_counts is None:
request.session['notify_counts'] = 1
else:
request.session['notify_counts'] +=1
Also you could use try...except pattern as follows:
def post(request, ...):
try:
request.session['notify_counts'] +=1
except KeyError:
request.session['notify_counts'] = 1
Hi i need to render the data on two templates from one function my code is
def stylepoints(request):
a=Product.objects.all()[:3]
cursor = connection.cursor()
try:
cursor.execute("SELECT facebook_id,name FROM django_facebook_facebookuser WHERE user_id = %s ORDER BY RAND() LIMIT 1",[request.user.id])
except Exception as e:
return HttpResponse("error in fetching Friends")
rows_affected=cursor.rowcount
if rows_affected > 0:
row1 = cursor.fetchall()
row12 = row1[0]
else:
row12 = ''
value = request.user.id
cursor12 = connection.cursor()
cursor12.execute("SELECT Distinct email FROM myaccount_invitation WHERE reference_id = %s AND status = 1 AND invitation_type = 2",[value])
friend = cursor12.fetchall()
if friend:
friends = friend[0]
return render_to_response('swf.html',{'a':a,'userf':row12,'friendshow':friend} , context_instance=RequestContext(request))
like in this i have send a data to one template name as
swf.html
but i need to send the data also to another template such as
swf2.html
please tell me can i render a data to two templates
def view1(request):
template_name='swf1.html'
return stylepoints(request, template_name)
def view2(request):
template_name='swf2.html'
return stylepoints(request, template_name)
def stylepoints(request, template_name):
a=Product.objects.all()[:3]
cursor = connection.cursor()
try:
cursor.execute("SELECT facebook_id,name FROM django_facebook_facebookuser WHERE user_id = %s ORDER BY RAND() LIMIT 1",[request.user.id])
except Exception as e:
return HttpResponse("error in fetching Friends")
rows_affected=cursor.rowcount
if rows_affected > 0:
row1 = cursor.fetchall()
row12 = row1[0]
else:
row12 = ''
value = request.user.id
cursor12 = connection.cursor()
cursor12.execute("SELECT Distinct email FROM myaccount_invitation WHERE reference_id = %s AND status = 1 AND invitation_type = 2",[value])
friend = cursor12.fetchall()
if friend:
friends = friend[0]
return render_to_response(template_name,{'a':a,'userf':row12,'friendshow':friend} , context_instance=RequestContext(request))