Sleekxmpp with Django not working? - django

Am working with sleekxmpp with python for sending messages and its working perfectly.Now i need to implement same in django to create web api for my mobile application.
When i implement that code in django its not getting connected to ejabberd server.xmpp=self.aaaa(jid,password,receiver,message) this function is throughing none value.
Below is my code in django:
class SendMessageView(APIView,sleekxmpp.ClientXMPP):
def aaaa(self,jid, password, recipient, message):
print "dddddddddddddddddddddddddddddddd",jid,password
sleekxmpp.ClientXMPP.__init__(self, jid, password)
self.recipient = recipient
self.msg = message
self.add_event_handler("session_start", self.start)
def start(self, event):
self.send_presence()
try:
self.get_roster()
except IqError as err:
logging.error('There was an error getting the roster')
logging.error(err.iq['error']['condition'])
self.disconnect()
except IqTimeout:
logging.error('Server is taking too long to respond')
self.disconnect()
self.send_message(mto=self.recipient,mbody=self.msg,mtype='chat')
self.disconnect(wait=True)
def post(self,request,format=None):
serializer=SendMessageSerializer(request.DATA)
jid=request.DATA.get('sender')
password=request.DATA.get('password')
receiver=request.DATA.get('receiver')
message=request.DATA.get('message')
print "ddddddddddddd",jid,password,receiver,message
xmpp=self.aaaa(jid,password,receiver,message)
print "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",xmpp
xmpp.register_plugin('xep_0030')
xmpp.register_plugin('xep_0199')
if xmpp.connect():
xmpp.process(block=False)
print "Connected"
else:
print "Not Connected"
Error shown is:
AttributeError at /chat-message/send/
'NoneType' object has no attribute 'register_plugin'
Request Method: POST
Request URL: ******/chat-message/send/
Django Version: 1.6
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'register_plugin'
Exception Location: /home/ntech/projects/project_path/apps/chats/views.py in post, line 58
Python Executable: /home/ntech/Virtualenv/project_path/bin/python
Python Version: 2.7.6
Python Path:
['/home/ntech/projects/chatline',
'/home/ntech/Virtualenv/project_path/lib/python2.7',
'/home/ntech/Virtualenv/project_path/lib/python2.7/plat-i386-linux-gnu',
'/home/ntech/Virtualenv/project_path/lib/python2.7/lib-tk',
'/home/ntech/Virtualenv/project_path/lib/python2.7/lib-old',
'/home/ntech/Virtualenv/project_path/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-i386-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/ntech/Virtualenv/project_path/local/lib/python2.7/site-packages',
'/home/ntech/Virtualenv/project_path/lib/python2.7/site-packages']
Server time: Mon, 29 Dec 2014 06:02:10 +0000

Your method aaaa always return None. Try to use self.
Also it is not a good idea to multiple inheritance here. Try aggregation
class SendMessageView(APIView):
def aaaa(self,jid, password, recipient, message):
...
self.xmpp = sleekxmpp.ClientXMPP(jid, password)
...
def post(self,request,format=None):
...
self.aaaa(jid,password,receiver,message)
self.xmpp.register_plugin('xep_0030')
self.xmpp.register_plugin('xep_0199')
...
Or even better:
class SendMessageView(APIView):
def get_xmpp(self,jid, password, recipient, message):
...
return sleekxmpp.ClientXMPP(jid, password)
...
def post(self,request,format=None):
...
xmpp = self.get_xmpp(jid,password,receiver,message)
xmpp.register_plugin('xep_0030')
xmpp.register_plugin('xep_0199')
...

Related

Django API throws Exception Value: Object of type ParserError is not JSON serializable, does not enter the try block

New to development of API. Any help or article would really help.
my views.py
#api_view(["POST"])
def retrieve_base64_as_pdf(request):
try:
#base_64_input = request.POST.get('ImageBase64String')
body_unicode = request.body.decode('utf-8')
print(len(body_unicode))
body = json.loads(body_unicode)
print(len(body))
base_64_input = body['ImageBase64String']
doc_ref_id = body['DocRefID']
#base_64_input = json.loads(request.body["ImageBase64String"])
pdf = base64.b64decode(base_64_input)
#build PDF
with open(os.path.expanduser('life/lpo-test.pdf'), 'wb') as fout:
fout.write(pdf)
responses = single_page_extractor(file_names='life/lpo-test.pdf',client_doc_ref_id=doc_ref_id)
# return Response(responses, safe=False)
return Response(responses, status=status.HTTP_200_OK)
# responses = json.responses.replace("\'", '')
# return Response(responses, status=status.HTTP_200_OK, content_type='json')
except ValueError as e:
os.remove('life/lpo-test.pdf')
return Response(e, status=status.HTTP_400_BAD_REQUEST)
my process,
1. consume base 64 run my logic and output json.
It works 99% of the time but throws bad request at times.
1. The json input is the same for all inputs.
error message:
exception: Exception Value: Object of type ParserError is not JSON serializable
The only error:
ParserError('Error tokenizing data. C error: Expected 1 fields in line 3, saw 12\n')
Looks like Response class if from django-rest-framework and it will try to jsonify any input data you gave it.
On the last line you are trying to serialize error object and that's why you have a problem:
return Response(e, status=status.HTTP_400_BAD_REQUEST)
Try to wrap error into str to make in json-serializable:
return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
Also the problem might be in single_page_extractor if it can return error objects.

Cannot assign "<SimpleLazyObject

class ProductDetailSlugview(ObjectViewedMixin, DetailView):
queryset = Product.objects.all()
template_name = "products/product_detail.html"
def get_context_data(self, *args, **kwargs):
context=super(ProductDetailSlugview, self).get_context_data(*args , **kwargs)
cart_object, new_object = Cart.objects.new_or_get(self.request)
context['cart']=cart_object
return context
this is my view
ValueError at /product/list/blackberry Cannot assign
"
at 0x7f0488733860>>": "ObjectViewed.user" must be a "User" instance.
Request Method: GET Request
URL: http://127.0.0.1:8000/product/list/blackberry Django
Version: 2.1.3 Exception Type: ValueError Exception Value: Cannot
assign "
object at 0x7f0488733860>>": "ObjectViewed.user" must be a "User"
instance. Exception
Location: /home/wiwigi/Desktop/django-virtual/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py
in set, line 210 Python
Executable: /home/wiwigi/Desktop/django-virtual/bin/python3 Python
Version: 3.6.5 Python Path: ['/home/wiwigi/Desktop/ecommerce_sample',
'/home/wiwigi/Desktop/ecommerce_sample',
'/home/wiwigi/Desktop/django-virtual/lib/python36.zip',
'/home/wiwigi/Desktop/django-virtual/lib/python3.6',
'/home/wiwigi/Desktop/django-virtual/lib/python3.6/lib-dynload',
'/usr/lib/python3.6',
'/home/wiwigi/Desktop/django-virtual/lib/python3.6/site-packages',
'/home/wiwigi/pycharm-2018.1.2/helpers/pycharm_matplotlib_backend']
Server time: mar, 26 Fév 2019 11:31:14 +0000
and my error code please help me
You are assigning an AnonymousUser object to the attribute user of an ObjectViewed instance. From the naming, my guess is that this happens in the ObjectViewedMixin.
For a more definite answer, you have to post the full stack trace and the relevant code.
This is because of you are accessing this view with out login (So it shows AnonymousUser) so you need to add LoginRequiredMixin to your class as below to ensure that only logged in users can visit this view.
from django.contrib.auth.mixins import LoginRequiredMixin
class ProductDetailSlugview(LoginRequiredMixin, ObjectViewedMixin, DetailView):
# rest of the code

Django 1.7 matching query does not exist

I have the following error when I try to create a class-based view to Modify my model Destino.
If possible I would do without using slug or pk in the urls.py
Error:
Destino matching query does not exist.
Request Method: GET
Request URL: http://localhost:8002/modificarVC/modificar.html
Django Version: 1.7
Exception Type: DoesNotExist
Exception Value:
Destino matching query does not exist.
Exception Location: /usr/local/lib/python2.7/dist-packages/Django-1.7- py2.7.egg/django/db/models/query.py in get, line 357
Python Executable: /usr/bin/python
Python Version: 2.7.6
Python Path:
['/home/juanma/Escritorio/exPWfebrero/Django/AgenciaViajes',
'/usr/local/lib/python2.7/dist-packages/Django-1.7-py2.7.egg',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PILcompat',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode']
URLS:
url(r'^modificarVC/modificar.html', modificarVC.as_view(), name='modificarDestino'),
VIEWS:
class modificarVC(UpdateView):
model = Destino
template_name = "modificarVC/modificar.html"
success_url = '/'
def get_object(self):
return Destino.objects.get(pk=self.request.GET.get('pk'))
As stated in some comments, you've done a few things that go against the power of class based views. In regards to the UpdateView which you're using, it's expecting a pk to be passed in.
# urls.py
url(r'^modificarVC/modificar/(?P<pk>\d+)/$', modificarVC.as_view(), name='modificarDestino')
When you hit a URL such as /modificarVC/modificar/5/ the UpdateView automatically sets the object by selected the object in your model Destino that has an id of 5.
# views.py
class modificarVC(UpdateView):
model = Destino
template_name = "modificarVC/modificar.html"
success_url = '/'
your error message hints at problem -- your request url didn't include a 'pk' request parameter (see 'Request URL')
Destino matching query does not exist.
Request Method: GET
Request URL: http://localhost:8002/modificarVC/modificar.html
run your request again, but add the pk parameter to the end as a query parameter: http://localhost:8002/modificarVC/modificar.html?pk=42

Python restkit module connection returns error

I'm attempting to use a script I found online, (https://confluence.atlassian.com/display/DOCSPRINT/The+Simplest+Possible+JIRA+REST+Examples) probably 5+ years old, to access Jira REST API. I have all the modules installed in Pyhton 2.7. However, when run the script I get an error that SimplePool cannot be imported. Having done my Goodiligence (Google searching), I see that SimplePool is deprecated in restkit 4.2.2 (which is the version I have installed). So, the doc that I found (http://pydoc.net/Python/restkit/2.3.0/restkit.pool.simple/) says to use TConnectionManager (which I did with no success). I still get a similar error. So, I stumbled upon another doc (http://benoitc.github.io/restkit/pool.html) and it says to use ConnectionPool, and I still get a similar error. I appreciate any direction given. Here is my code:
import simplejson as json
from restkit import * #added this line after finding the last document
from restkit import Resource, BasicAuth, request
from socketpool import ConnectionPool
SimplePool = ConnectionPool
def rest_test(server_base_url, user, password, issue_key):
'''
Use restkit to make a REST request to JIRA
'''
verbose = False
# A pool of connections
pool = SimplePool(factory=Connection)
# This sends the user and password with the request.
auth = BasicAuth(user, password)
resource_name = "issue"
complete_url = "%s/rest/api/latest/%s/%s" % (server_base_url, resource_name, issue_key)
resource = Resource(complete_url, pool_instance=pool, filters=[auth])
try:
response = resource.get(headers = {'Content-Type' : 'application/json'})
except Exception,ex:
# ex.msg is a string that looks like a dictionary
print "EXCEPTION: %s " % ex.msg
return
# Most successful responses have an HTTP 200 status
if response.status_int != 200:
print "ERROR: status %s" % response.status_int
return
# Convert the text in the reply into a Python dictionary
issue = json.loads(response.body_string())
# Pretty-print the JSON
if verbose:
print json.dumps(issue, sort_keys=True, indent=4)
# The properties of the issue include:
# self, html, key, transitions, expand, fields
print "Issue key: %s" % issue['key']
fields = issue['fields']
for field_name in fields:
field_object = fields[field_name]
print "Field %s = %s" % (field_name, field_object['type'])
# The type of the value of a field depends on the type of the field
if field_name in ["summary"]:
print " Value = %s" % field_object['value']
if __name__ == '__main__':
user = 'myuname'
password = '*****'
server_url = 'http://jira.mysite.com/'
issue_key = 'JRA-219'
rest_test(server_url, user, password, issue_key)
Here is the error returned:
File "simplest_client.py", line 30, in rest_test
pool = SimplePool()
TypeError: __init__() takes at least 2 arguments (1 given)
EXCEPTION: <?xml version="1.0" encoding="UTF-8" standalone="yes"?><status><status-code>404</status-code><message>null for uri: http://jira.mysite.com//rest/api/latest/issue/JRA-219</message></status>

django-nocaptcha-recaptcha always shows additional verification box

I installed django-nocaptcha-recaptcha and integrated it into my form:
from nocaptcha_recaptcha.fields import NoReCaptchaField
class ClientForm(forms.ModelForm):
captcha = NoReCaptchaField()
It shows up fine on the form, but whenever I click on it an additional dialog pops up asking to enter some text and verify. It happens every time. I tested it from another computer on another network and it still asks for additional verification after clicking the box.
This is what it looks like: additional verification dialog box
Here's how I'm handling the form:
#xframe_options_exempt
def registration(request):
if request.method == 'POST':
clientform = ClientForm(request.POST)
# check whether it's valid:
if clientform.is_valid():
new_client = clientform.save()
...
What am I doing wrong? Is it a problem with django-nocaptcha-recaptcha? Should I use something else?
P.S. I'm using django 1.7.1 with python 3.4
Another alternative: Minimalist and non framework dependant.
This is the code, in case you want to rewrite it.
'''
NO-CAPTCHA VERSION: 1.0
PYTHON VERSION: 3.x
'''
import json
from urllib.request import Request, urlopen
from urllib.parse import urlencode
VERIFY_SERVER = "www.google.com"
class RecaptchaResponse(object):
def __init__(self, is_valid, error_code=None):
self.is_valid = is_valid
self.error_code = error_code
def __repr__(self):
return "Recaptcha response: %s %s" % (
self.is_valid, self.error_code)
def __str__(self):
return self.__repr__()
def displayhtml(site_key, language=''):
"""Gets the HTML to display for reCAPTCHA
site_key -- The site key
language -- The language code for the widget.
"""
return """<script src="https://www.google.com/recaptcha/api.js?hl=%(LanguageCode)s" async="async" defer="defer"></script>
<div class="g-recaptcha" data-sitekey="%(SiteKey)s"></div>
""" % {
'LanguageCode': language,
'SiteKey': site_key,
}
def submit(response,
secret_key,
remote_ip,
verify_server=VERIFY_SERVER):
"""
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
response -- The value of response from the form
secret_key -- your reCAPTCHA secret key
remote_ip -- the user's ip address
"""
if not(response and len(response)):
return RecaptchaResponse(is_valid=False, error_code='incorrect-captcha-sol')
def encode_if_necessary(s):
if isinstance(s, str):
return s.encode('utf-8')
return s
params = urlencode({
'secret': encode_if_necessary(secret_key),
'remoteip': encode_if_necessary(remote_ip),
'response': encode_if_necessary(response),
})
params = params.encode('utf-8')
request = Request(
url="https://%s/recaptcha/api/siteverify" % verify_server,
data=params,
headers={
"Content-type": "application/x-www-form-urlencoded",
"User-agent": "reCAPTCHA Python"
}
)
httpresp = urlopen(request)
return_values = json.loads(httpresp.read().decode('utf-8'))
httpresp.close()
return_code = return_values['success']
if return_code:
return RecaptchaResponse(is_valid=True)
else:
return RecaptchaResponse(is_valid=False, error_code=return_values['error-codes'])
Restart the server and don't forget to clear your browser's cache. Hope this helps.