i have a django website that runs a chatbot app to simulate a customer service by getting the question and retrieving the best match reply in the DB using queries.
view.py:
#csrf_exempt
def home(request):
context= locals()
template= 'home.html'
return render(request,template,context)
#csrf_exempt
def male_chatbot(request):
if not request.session.session_key:
request.session.create()
context= locals()
template= 'male_chatbot.html'
return render(request,template,context)
#csrf_exempt
def run_python_male(request):
if request.method == "POST":
session_key = request.session.session_key
param11 = request.POST.get('param1')
msg = chatbot.run_conversation_male(param11)
return JsonResponse({ 'msg': msg})
chatbot.py:
raw_chatting_log =[]
chatting_log =[]
def chatting_log_data(raw_Input,Input,check):
if check== "check":
if raw_Input in raw_chatting_log:
return True
else:
return False
else:
if check== "app":
raw_chatting_log.append(raw_Input)
chatting_log.append(Input)
def check_lastB():
new='جديد'
if len(raw_chatting_log) == 0:
return new
else:
return raw_chatting_log[-1]
def delandsave_chat_log():
name= str(uuid.uuid4())
thefile = open('/home/mansard/webapps/gadgetron/src/chatting_logs/'+name+'.txt', 'w')
for item in chatting_log:
thefile.write("%s\n" % item)
thefile.close()
raw_chatting_log.clear()
chatting_log.clear()
def run_conversation_male(user_in):
last_B = check_lastB()
H = user_in
NN1= "H:"+str(user_in)
New_H= ' '.join(PreProcess_text(H))
if last_B== 'تقييمك للمحادثة و الخدمة؟':
#do_somthing
else:
if chatting_log_data(H,NN1,"check") == True:
#do_somthing
else:
#find_replay
So, the idea is saving the input/output conversation in two list :
raw_chatting_log ==> hold the data with out the addition 'H:' or 'B:' just a the input and output.to help the chatbot remembering the asked questions and using it in chatting_log_data(H,NN1,"check").
chatting_log=> will hold the the conversation to the chat log in form of 'H:' and 'B:' to save the whole list when the user ends the conversation or close the page in def delandsave_chat_log()
and for last_B helps me know what is the chatbot's last responce
So far it is working for one user, now what i'm thinking is switching to make it handle or chat with many users at the same time where each user has it own chatbot.run_conversation_male and each chat/conversation is separate each with it own chatting log list so that i can use it for checking and saving the data.
Related
I am trying to run my flask app, but every time I load my index page, it gives me the error:
AttributeError: 'Flask' object has no attribute 'login_manager'.
It works before I put in this specific code
bp = flask.Blueprint("bp", __name__, template_folder="./build")
#bp.route('/index')
#login_required
def index():
# TODO: insert the data fetched by your app main page here as a JSON
DATA = {"your": "data here"}
data = json.dumps(DATA)
return flask.render_template(
"index.html",
data=data,
)
app.register_blueprint(bp)
This is my current code where it does work
#app.route("/index", methods=["GET", "POST"])
def index():
global current_user
if not current_user:
return flask.redirect(flask.url_for("login"))
if flask.request.method == "GET":
track_name, genius_link, track_artist, track_image, track_url = render()
# If user has no favorite artists, redirect back to profile.
if track_name == None:
return flask.redirect(flask.url_for("profile"))
return flask.render_template(
"index.html",
variable=track_name,
variable1=genius_link,
variable2=track_artist,
variable3=track_image,
variable4=track_url,
)
else:
valid_artist = validate_and_insert_artist(flask.request.form["artistId"])
if not valid_artist:
return flask.render_template("index.html", error=True)
else:
track_name, genius_link, track_artist, track_image, track_url = render()
# If user has no favorite artists, redirect back to profile.
if track_name == None:
return flask.redirect(flask.url_for("profile"))
return flask.render_template(
"index.html",
variable=track_name,
variable1=genius_link,
variable2=track_artist,
variable3=track_image,
variable4=track_url,
)
I am not sure why as soon as I put in the blueprint code, it stops working and gives me that error
This is my login.html
#app.route("/login", methods=["GET", "POST"])
def login():
global current_user
if current_user:
return flask.redirect(flask.url_for("profile"))
if flask.request.method == "GET":
return flask.render_template("login.html")
if flask.request.method == "POST":
username = flask.request.form["username"]
cursor.execute(
"SELECT user_name FROM public.users WHERE user_name = %s", [username]
)
results = cursor.fetchall()
if len(results) != 0: # if a user exists, "log" them in
current_user = username
return flask.redirect(flask.url_for("profile"))
else:
return flask.render_template("login.html", error=True)
You need to read the Flask documentation for #login_required. As soon as you've added a method that requires the user to be logged in, you need to provide a method by which the user can log in.
Or perhaps you just want to delete the #login_required?
I'm new to Django's testing and trying to write test functions for views, but I don't get the whole test view thing, I've seen a lot of examples but it seems to be to difficult, I need an example on something I wrote to get the idea.
here's a function I want to test its post and get:
def ForgetPasswordRegistry(self, request):
forgetpassword = True
if request.method == 'GET':
if 'UserID' in request.session:
forgetpassword = False
return request, forgetpassword
elif request.method == 'POST':
email = request.POST['email']
if self.IsUserExist(email):
forget = models.ForgetPasswordRegistry()
forget.UserID = self.GetUser(email)
forget.Access = 1
session = random.randint(999999999999999, 9999999999999999999999999999999999)
forget.Session = str(session)
link = 'http://127.0.0.1:8000/home/resetpassword/' + forget.Session
self.SendEmail('Reset-Password', link, [forget.UserID.Email])
forget.save()
FeedBack = ' Check Your Mail You Got A Recovery Mail'
AlertType = 'alert-success'
return request, AlertType, None, FeedBack, None, None
else:
AlertType = 'alert-danger'
ModalFeedBack = 'This Email Dose Not Exist'
EmailErrors = 'This Email Dose Not Exist'
return request, AlertType, forgetpassword, None, EmailErrors, ModalFeedBack
Don't let the concept of views confuse you!! Essentially there is a python function that you need to exercise certain conditionals of.
It looks like there are 4 main branches:
GET not in session
GET in session
POST exists
POST does not exist
so there should probably be at least 4 different tests. I'll post the first one because it is pretty straightforward:
def ForgetPasswordRegistry(self, request):
forgetpassword = True
if request.method == 'GET':
if 'UserID' in request.session:
forgetpassword = False
return request, forgetpassword
def test_forget_get_user_id_in_session(self):
request = Mock(session={'UserID': 'here'}, method='GET')
# instantiate your view class
yourview = YourView()
sefl.assertEqual(yourview.ForgetPasswordRegistry(request), (request, False))
The post user exists branch is a little more complicated because there are more things that the test needs to account for, and potentially provide stub implementations for:
SendEmail
GetUser
models.ForgetPasswordRegistry()
Use Django's test client: https://docs.djangoproject.com/en/stable/topics/testing/tools/#the-test-client
Example:
from django.test import Client, TestCase
class ViewTestCase(TestCase):
def test_post_creation(self):
c = Client() # instantiate the Django test client
response = c.get('/forgetpassword/')
self.assertEqual(response.status, 200)
I have a Django template that has data from a few different model types combining to make it. A dashboard if you will. And each of those has an edit form.
Is it best to process all those forms in one view as they are posted back to the same place and differentiating between them by a unique field like below?
Or if having lots of different dedicated avenues is the way forward? Thanks for any guidance
class ProjectDetail(DetailView):
template_name = 'project/view.html'
def get_object(self):
try:
return Project.objects.filter(brief__slug=self.kwargs['slug']).filter(team=get_user_team(self.request)).first()
# add loop to allow multiple teams to work on the same brief (project)
except Exception as e:
project_error = '%s (%s)' % (e.message, type(e))
messages.error(self.request, 'OH NO! %s' % project_error)
return redirect('home')
def get_context_data(self, **kwargs):
project = self.get_object()
context = dict()
context['project'] = project
context['milestone_form'] = MilestoneForm(initial={'project': project})
context['view'] = self
return context
def post(self, request, *args, **kwargs):
# get the context for the page
context = self.get_context_data()
try:
# switch for each of the form types on the team profile page (shown if member)
if 'milestone_form_submit' in request.POST:
project=self.get_object()
# set date arbitrarily to half way to brief deadline
brief = Brief.objects.get(project=project)
last_milestone = self.milestones().last()
milestone_del_date = last_milestone.del_date + timedelta(days=7)
new_milestone = Milestone(
project=project,
title_text=request.POST.get('title_text'),
del_date=milestone_del_date,
)
try:
new_milestone.save()
messages.success(self.request, "Excellent! New delivery popped on the bottom of the list")
except Exception as e:
# pass the erroring form back in the context if not
form = MilestoneForm(request.POST)
context['milestone_form'] = form
messages.error(self.request, "OH NO! Deadline didn't save. Be a sport and check what you entered")
elif 'milestone-edit-date-form-submit' in request.POST:
# get object from db
milestone = Milestone.objects.get(pk=request.POST['id'])
# update del_date field sent
milestone.del_date = request.POST['del_date']
# save back to db
milestone.save()
messages.success(self.request, "Updated that delivery right there!")
elif ...
except Exception as e:
messages.error(self.request, "OH NO! Deadline didn't save. Be a sport and check what you entered")
return render(request, self.template_name, context)
You can use mixins in order to solve your problem.
Example from the gist https://gist.github.com/michelts/1029336
class MultipleFormsMixin(FormMixin):
"""
A mixin that provides a way to show and handle several forms in a
request.
"""
form_classes = {} # set the form classes as a mapping
def get_form_classes(self):
return self.form_classes
def get_forms(self, form_classes):
return dict([(key, klass(**self.get_form_kwargs())) \
for key, klass in form_classes.items()])
def forms_valid(self, forms):
return super(MultipleFormsMixin, self).form_valid(forms)
def forms_invalid(self, forms):
return self.render_to_response(self.get_context_data(forms=forms))
As you can see, when you inherit from this class, you can handle multiple forms simultaneously. Look at the gist's code and adapt it to your problem.
Look at this answer
I want to write test for my code and pass a value to a form how can i do that? I have two form in my code and this value should pass just to one of them.
my unittest:
def test_user_has_project(self):
resp = self.client.post('/register/', NEW_USER)
self.assertRedirects(resp, '/register/confirm/')
confirmation_code = self.client.session['confirm_code']
resp = self.client.post('/register/confirm/',
{'confirm_code':confirmation_code})
but this code pass confirmation code to both forms.
my views:
if request.method == 'POST':
form = forms.RegistrationConfirmForm(request.POST)
if (form.is_valid() and
form.cleaned_data['confirm_code'] == request.session['confirm_code']):
# Register the user in the backend
form = forms.RegistrationForm(request.session['registering_user'])
sorry. I'm a beginner in both coding and asking question!
This question might appear to be a duplicate and/or too boring. I have already read this, this, this, this and this questions & answers. But couldn't find solution that fits to my problem.
I'm new to Django framework. To learn it I want to create simple blog. When user clicks Register button (after filling required fields), following error thrown:
ValueError at /user/register/ The view user.views.register didn't
return an HttpResponse object. It returned None instead.
views.py
def register(request):
"""
Registers new user.
"""
if request.POST:
if request.method == 'POST':
personal_info = UserFormModel(request.POST)
if personal_info.is_valid():
email = personal_info.cleaned_data['email']
username = personal_info.cleaned_data['username']
if User.objects.filter(email=email).exists():
return HttpResponse('email error')
elif User.objects.filter(username=username).exists():
return HttpResponse('username error')
else:
return HttpResponse('saved')
else:
personal_info = UserFormModel()
return render_to_response('user/registration.html',
{
'title': 'Registration',
'username_error': 'Sorry, someone already has that username.',
'personal_info': personal_info,
},
context_instance=RequestContext(request))
If necessary I can share any files content.
Any helpful comment or answer would be appreciated.
In line
if personal_info.is_valid():
if personal info is not valid, it will return None.(return nothing)
add an else condition, because you are not handling a case.
if personal_info.is_valid():
# code here
else:
return HttpResponse('personal info provided not valid')
One of the better ways to handle situations like this from not occurring is to keep a dictionary for status message and result initialised at the start of the function, and return only at a single place instead of returning at multiple places, and storing result in result_dict.
result_dict = {'status': False}
and always return at the end of the function
return HttpResponse(json.dumps(result_dict))
This way you will never miss a case in returning values.
So Final code should look like
def register(request):
"""
Registers new user.
"""
result_dict = {'status': False}
if request.POST:
if request.method == 'POST':
personal_info = UserFormModel(request.POST)
if personal_info.is_valid():
email = personal_info.cleaned_data['email']
username = personal_info.cleaned_data['username']
if User.objects.filter(email=email).exists():
result_dict['message'] = 'email error'
elif User.objects.filter(username=username).exists():
result_dict['message'] = 'username error'
else:
result_dict['message'] = 'saved'
result_dict['status'] = True
else:
result_dict['message'] = 'personal info provided not valid'
else:
personal_info = UserFormModel()
return render_to_response('user/registration.html',
{
'title': 'Registration',
'username_error': 'Sorry, someone already has that username.',
'personal_info': personal_info,
},
context_instance=RequestContext(request))
return HttpResponse(json.dumps(result_dict))