I am new for Django1.10 Python.
I've to provide web services for an app. So I created a web service in python's Django framework. The web service is properly working for iOS but getting issue while handling with android. For dealing with web services in android, using Volley library.
Following error occurring:-
Error Code 500 Internal Server Error
So unable to POST data through android end...
For Web service I am using following code :-
views.py
from django.http import HttpResponseRedirect, HttpResponse
from django.views.decorators import csrf
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.db import IntegrityError, connection
from django.views.decorators.cache import cache_control
from django.core.files.images import get_image_dimensions
import json
from json import loads, dump
from models import Gym
#csrf_exempt
def gym_register_web(request):
data = json.loads(request.body)
gN = str(data['gym_name'])
gPh = str(data['gym_phone'])
gE = str(data['gym_email'])
gL = str(data['gym_landmark'])
gAdd = str(data['gym_address'])
exE = Gym.objects.filter(gym_email = gE)
if exE:
status = 'failed'
msg = 'EmailId already exist'
responseMsg = '{\n "status" : "'+status+'",\n "msg" : "'+msg+'"\n}'
return HttpResponse(responseMsg)
else:
gymI = Gym(gym_name = gN, gym_phone = gPh, gym_email = gE, gym_area = gL, gym_address = gAdd)
gymI.save()
data = Gym.objects.get(gym_email = gE)
status = 'success'
dataType = 'gym_id'
val = str(data.gym_id)
responseMsg = '{\n "status" : "'+status+'",\n "'+dataType+'" : "'+val+'"\n}'
return HttpResponse(responseMsg)
urls.py
from django.conf.urls import url, include
from . import views
from django.views.decorators.csrf import csrf_protect, csrf_exempt
admin.autodiscover()
urlpatterns=[
url(r'^gymRegister/$', views.gym_register_web),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
EDIT:
models.py
from django.db import models
from django.contrib import admin
class Gym(models.Model):
gym_id = models.AutoField(primary_key = True)
gym_name = models.CharField(max_length = 100, null=True,default = None )
gym_email = models.CharField(max_length = 100, null=True,default = None )
gym_phone = models.BigIntegerField(null=True,default = None )
gym_area = models.TextField(max_length = 255, null=True,default = None )
gym_address = models.TextField(max_length = 255, null=True,default = None )
gym_latitude = models.CharField(max_length = 100, null=True,default = None )
gym_longitude = models.CharField(max_length = 100, null=True,default = None )
gym_status = models.IntegerField(null=True,default = None )
gym_website = models.CharField(max_length = 255,null=True,default = None )
gym_ladies_special = models.IntegerField(null=True,default = None )
I tested web service on Advance REST Client providing desired output,
and I would like to remind once again the web service is properly working for iOS
So, Where Should I improve my code...?
Thanks in Advance :)
EDIT:
my android developer trying to send data in json object manner
{ "key1"="val1", "key2"="val2"}
instead sending it in json array(key:value) manner
{
"key1" : "val1",
"key2" : "val2"
}
How can I fetch data sent in object format...
ThankYou
Make sure that in your 'request.body', you are getting a proper dictionary which have all the keys u accessed below.Because,if your 'data' variable dont have any key that you accessed below, it will raise keyerror and u didnt handle keyerror in your code.
If above does not worked, then show me your models.py
Related
import torch
# import joblib
from torch.utils.mobile_optimizer import optimize_for_mobile
from torchvision.models.vgg import vgg16
import torch, torchvision.models
# lb = joblib.load('lb.pkl')
device = torch.device('cuda:0')
#device = torch.device('cpu')#'cuda:0')
torch.backends.cudnn.benchmark = True
model = vgg16().to(device)
# model = torchvision.models.vgg16()
path = 'model-22222.pth'
torch.save(model.state_dict(), path) # nothing else here
model.load_state_dict(torch.load(path))
#model.load_state_dict(torch.load('./model-76-0.7754.pth'))
scripted_module = torch.jit.script(model)
optimized_scripted_module = optimize_for_mobile(scripted_module)
optimized_scripted_module._save_for_lite_interpreter("model-76-0.7754.ptl")
The optimize_for_mobile seems does not make the ptl file smaller, it's about 527M, too large on Android. How to make it smaller?
You may try using quantization:
https://pytorch.org/docs/stable/quantization.html
Usually it allows to reduce the size of the model 2x-4x times with little or no loss of accuracy.
Example:
import torch
from torch.utils.mobile_optimizer import optimize_for_mobile
from torchvision.models.vgg import vgg16
device = torch.device("cpu")
torch.backends.cudnn.benchmark = True
model = vgg16().to(device)
backend = "qnnpack"
model.qconfig = torch.quantization.get_default_qconfig(backend)
torch.backends.quantized.engine = backend
model_static_quantized = torch.quantization.prepare(model, inplace=False)
model_static_quantized = torch.quantization.convert(
model_static_quantized, inplace=False
)
scripted_module = torch.jit.script(model_static_quantized)
optimized_scripted_module = optimize_for_mobile(scripted_module)
optimized_scripted_module._save_for_lite_interpreter("model_quantized.ptl")
Apart from it I would try to use the architectures more suitable for mobile phones because VGG is kinda old and has not a great size/accuracy ratio. You can distillate your trained VGG model into smaller one with Knowledge distillation.
I'm using the android sdk generated by AWS API Gateway to get a pre-signed URL for objects in s3 (lambda behind API gateway).
My s3 bucket looks like this:
* module_a
|\
| * file_a
| * subdir_a
| \
| * file_sa
* module_b
This works perfectly for file_a, but for file_sa it doesn't. At least not when I use the android SDK, there I get an URL where the slash is replaced with %25252F.
However, when I test the api in the console, I get the correct URL.
Is there anything I can do with the SDK to fix this?
Update
Here's the chain of code snippets involved in this problem.
Android code to download file (exception happens in last line)
fileName = "css/style.css"; // file in s3
moduleName = "main"; // folder in s3
[...]
ApiClientFactory factory = new ApiClientFactory().credentialsProvider(
aws.credentialsProvider);
apiClient = factory.build(myAPIClient.class);
apiClient.modulesModuleFileGet(fileName.replace("/", "%2F"), moduleName);
URL url = new URL(url_path.getUrl());
URLConnection connection = url.openConnection();
connection.connect();
InputStream in = new BufferedInputStream(connection.getInputStream());
API Gateway
The api endpoint used above is configured with two path parameters (module name and file name). The body mapping template for the call to lambda looks like this:
#set($inputRoot = $input.path('$'))
{
"module" : "$input.params('module')",
"file": "$input.params('file')"
}
Lambda
from __future__ import print_function
import json
import urllib
import boto3
s3 = boto3.client('s3')
def lambda_handler(event, context):
key = event['module'] + "/" + event['file'].replace("%2F", "/")
url = s3.generate_presigned_url(
"get_object",
Params={'Bucket':"mybucket",
'Key': key},
ExpiresIn=60)
return {"url": url}
I've got it to work after following the comments. However I still somehow get double quoted slashes. Here's the working code
Android
public Url modulesModuleFileGet(String fileName, String moduleName) {
try {
String fileNameEnc = URLEncoder.encode(fileName, "UTF-8");
Url ret = getApiClient().modulesModuleFileGet(fileNameEnc, moduleName);
return ret;
} catch (UnsupportedEncodingException e){
Log.e(TAG, "> modulesModuleFileGet(", e);
return null;
}
}
Lambda
def lambda_handler(event, context):
key = event['module'] + "/" + urllib.unquote_plus(urllib.unquote_plus(event['file']))
url = s3.generate_presigned_url(
"get_object",
Params={'Bucket':"my",
'Key': key},
ExpiresIn=60)
return {"url": url}
I'd still welcome further suggestions on how to improve this, but for now it is working. Thanks for the comments pointing me in the right direction.
I am developing an API using DRF which accepts the Multiple Request from Headers of the URL, but the headers might change accordingly as the some times 1 header or sometimes 4 header.
So how can I design API, which processes the result according to the changing header.
This is the Image , from which the request is coming.
Or is there any other way from which i can handle this problem ?
Below is the code of sample normal header, which i used to process the header
from userregistration.models import Userregistration
from rest_framework import generics
from sub_category.models import Sub_category
from upload_image.models import Upload_image
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
class StatusCode(object):
OK = 200
NOT_FOUND = 404
import json
from django.http import HttpResponse
def JSONResponse(data = None, status = StatusCode.OK):
if data is None:
return HttpResponse(status)
if data and type(data) is dict:
return HttpResponse(json.dumps(data, indent = 4, encoding = 'utf-8', sort_keys = True), \
mimetype = 'application/json', status = status)
else:
return HttpResponse(status = StatusCode.NOT_FOUND)
def get_queryset(request):
category_id = request.META.get('HTTP_CATEGORY_ID')
from django.http import JsonResponse
import sys
details=[]
objects=Sub_category.objects.filter(category_id=category_id)
for obj in objects:
print sys.stderr,obj.image_id
if(obj.image_id != ""):
if(Upload_image.objects.filter(pk=obj.image_id).exists()):
image_details=Upload_image.objects.get(pk=obj.image_id)
image_link='http://res.cloudinary.com/9lc/imawere/***/appname/'+image_details.link
else:
image_link=""
else:
image_link=''
details.append({
'Sub-Categories':Sub_category.objects.filter(category_id=obj.category_id,sc_type=obj.sc_type).values('pk','category_id','sc_type')[0],
'image_link' : image_link
})
from django.http import JsonResponse
return JsonResponse(details,safe=False)
I am wondering how to adjust the standard user agent in my http requests. I am using the Volley library and I KNOW how to
set a new user agent
retrieve the default user agent as a string (e.g. "Dalvik/1.6.0 (Linux; U; Android 4.0.2; sdk Build/ICS_MR0") => System.getProperty("http.agent")
What I DON'T know is:
how to get the single elements this user agent is build of, so I can replace only the string "Dalvik/1.6.0" with a custom string.
Is that possible, or do I have to make a string replacement?
Thx
In order to set the user agent globally for all requests sent via volley, here is my solution:
When you are initializing the volley request queue, instead of using the convenient method Volley.newRequestQueue(Context);, use the following snippet:
private RequestQueue makeRequestQueue(Context context) {
DiskBasedCache cache = new DiskBasedCache(new File(context.getCacheDir(), DEFAULT_CACHE_DIR), DISK_CACHE_SIZE);
BasicNetwork network = new BasicNetwork(new MyHurlStack());
RequestQueue queue = new RequestQueue(cache, network);
queue.start();
return queue;
}
public static class MyHurlStack extends HurlStack {
#Override
public HttpResponse executeRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
if (additionalHeaders == null || Collections.emptyMap().equals(additionalHeaders) {
additionalHeaders = new HashMap<>();
}
additionalHeaders.put("User-Agent", "test_user_agent_in_volley");
return super.executeRequest(request, additionalHeaders);
}
}
This solution assumes you are targeting api level >= 9, so we use the HurlStack
The reason why this works is because in HurlStack.executeRequest(Request<?> request, Map<String, String> additionalHeaders) method, the stuff you add to the additionalHeaders would later be added to an HttpUrlConnection request property as in connection.addRequestProperty(headerName, map.get(headerName));
Yes,
Build.FINGERPRINT contains all the information you need,
https://developer.android.com/reference/android/os/Build.html
To get the individual parts, use the individual constant strings,
For detailed OS Version information use Build.VERSION
import android.util.Log;
import android.os.Bundle;
import android.os.Build;
public class MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Build","BOARD = "+Build.BOARD);
Log.i("Build","BOOTLOADER = "+Build.BOOTLOADER);
Log.i("Build","BRAND = "+Build.BRAND);
Log.i("Build","CPU_ABI = "+Build.CPU_ABI);
Log.i("Build","CPU_ABI2 = "+Build.CPU_ABI2);
Log.i("Build","DEVICE = "+Build.DEVICE);
Log.i("Build","DISPLAY = "+Build.DISPLAY);
Log.i("Build","FINGERPRINT = "+Build.FINGERPRINT);
Log.i("Build","HARDWARE = "+Build.HARDWARE);
Log.i("Build","HOST = "+Build.HOST);
Log.i("Build","ID = "+Build.ID);
Log.i("Build","MANUFACTURER = "+Build.MANUFACTURER);
Log.i("Build","MODEL = "+Build.MODEL);
Log.i("Build","PRODUCT = "+Build.PRODUCT);
Log.i("Build","RADIO = "+Build.RADIO);
Log.i("Build","SERIAL = "+Build.SERIAL);
Log.i("Build","TAGS = "+Build.TAGS);
Log.i("Build","TYPE = "+Build.TYPE);
Log.i("Build","USER = "+Build.USER);
Log.i("Build","BASE_OS = "+Build.VERSION.BASE_OS);
Log.i("Build","CODENAME = "+ Build.VERSION.CODENAME);
Log.i("Build","INCREMENTAL = "+ Build.VERSION.INCREMENTAL);
Log.i("Build","RELEASE = "+ Build.VERSION.RELEASE);
Log.i("Build","SDK = "+ Build.VERSION.SDK);
Log.i("Build","SECURITY_PATCH = "+ Build.VERSION.SECURITY_PATCH);
Log.i("$TAG#",Build.FINGERPRINT);
}
}
System.getProperty("http.agent") returns something like:
Dalvik/2.1.0 (Linux; U; Android 9; Android SDK built for x86 Build/PSR1.180720.075)
It's possible to build all the parts of this using a combination of android.os.Build and java.lang.System.getProperty().
This is an example of what's in android.os.Build running on an emulator:
Build.BOARD = "goldfish_x86"
Build.BOOTLOADER = "unknown"
Build.BRAND = "google"
Build.DEVICE = "generic_x86"
Build.DISPLAY = "sdk_gphone_x86-userdebug 9 PSR1.180720.075 5124027 dev-keys"
Build.FINGERPRINT = "google/sdk_gphone_x86/generic_x86:9/PSR1.180720.075/5124027:userdebug/dev-keys"
Build.HARDWARE = "ranchu"
Build.HOST = "abfarm904"
Build.ID = "PSR1.180720.075"
Build.MANUFACTURER = "Google"
Build.MODEL = "Android SDK built for x86"
Build.PRODUCT = "sdk_gphone_x86"
Build.SUPPORTED_32_BIT_ABIS = {"x86"}
Build.SUPPORTED_64_BIT_ABIS = {}
Build.SUPPORTED_ABIS = {"x86"}
Build.TAGS = "dev-keys"
Build.TIME = 1541887073000
Build.TYPE = "userdebug"
Build.USER = "android-build"
Build.UNKNOWN = "unknown"
Build.VERSION.BASE_OS = ""
Build.VERSION.CODENAME = "REL"
Build.VERSION.INCREMENTAL = "5124027"
Build.VERSION.PREVIEW_SDK_INT = 0
Build.VERSION.RELEASE = "9"
Build.VERSION.SDK_INT = 28
Build.VERSION.SECURITY_PATCH = "2018-09-05"
These properties are always provided by the Dalvik VM, according to Google's documentation:
file.separator = /
java.class.path = .
java.class.version = 50.0
java.compiler = Empty
java.ext.dirs = Empty
java.home = /system
java.io.tmpdir = /sdcard
java.library.path = /vendor/lib:/system/lib
java.vendor = The Android Project
java.vendor.url = http://www.android.com/
java.version = 0
java.specification.version = 0.9
java.specification.vendor = The Android Project
java.specification.name = Dalvik Core Library
java.vm.version = 1.2.0
java.vm.vendor = The Android Project
java.vm.name = Dalvik
java.vm.specification.version = 0.9
java.vm.specification.vendor = The Android Project
java.vm.specification.name = Dalvik Virtual Machine Specification
line.separator = \n
os.arch = armv7l
os.name = Linux
os.version = 2.6.32.9-g103d848
path.separator = :
user.dir = /
user.home = Empty
user.name = Empty
So, the default user agent appears to be composed of:
System.getProperty("java.vm.name") // Dalvik
System.getProperty("java.vm.version") // 2.1.0
System.getProperty("os.name") // Linux
"U" // not sure where to get this
"Android" // or this, probably safe to hard code though
Build.VERSION.RELEASE // 9
Build.MODEL // Android SDK built for x86
Build.ID // PSR1.180720.075
How to display JSON coming from php in intel App Framwork app. I have tried .getJSON() and .getJSONP() methods. Is there any full guide explaining these methods and how to use them?
Here are documentations for $.getJSON() and $.jsonP()
found the answer .
function getRaceData() {
var postBody = "";
postBody = "rid="+theRID;
var parameters = new AppMobi.Device.RemoteDataParameters();
parameters.url = "http://MyWebSite.com/php_src/getRaceData.php";
parameters.id = "1007";
parameters.method = "POST";
parameters.body = postBody;
jq.ui.showMask('loading race data');
AppMobi.device.getRemoteDataExt(parameters);
}
//then somewhere in your event handler, check the ID of the response and process the JSON....
case 1007: //got race data
var raceData = jq.parseJSON(event.response);
jq("#raceRCList").hide();
jq("#raceRCname").html(raceData.race_name);
jq("#raceRCdate").val(raceData.date);
jq("#raceRCstart").val(raceData.start_time);
jq("#raceRCData").show();
break;