How to connect a Django view with angular js Front end? - python

I'm fairly new to Django rest and angularjs. I'm trying to create a Django view which will have a function and this function has to be called via a button in angular js. Can anyone please help me out?
Thanks

This might help:
Django - Angular Tutorial
General answer would be:
1) Using for example Django REST expose your method (endpoint)
2) From Angular application send request to the previously exposed endpoint.

say this is your Django/python api end point (assume controller file to be random.py)
def getRandomInfo(request):
try:
result = database.getRandomInfo()
return JsonResponse(result, content_type="application/json", safe=False)
except Exception as e:
import traceback
traceback.print_exc(e)
return JsonResponse({error:'sorry'}, content_type="application/json", safe=False)
Via angular, provided you have resolved all the dependencies and have a functioning angular app and/or controller set up in your html/js
you can call the api using below code
app.controller("appControllerName", function ($scope, $http) {
$http.get("{% url 'getRandomInfo' %}")
.success(function (response, status) {
response_data = response
$scope.data = response_data;
}).error(function (response, status) {
$scope.status = status;
});
}
if you notice the {% url 'getRandomInfo' %} , this is defined in your urls.py , u'll have to add a line like this over there where getRandomInfo will have to be the 'name' of the url
url(r'^random/getRandomInfo/$',random.getRandomInfo, name='getRandomInfo'),
Over here you controller name is random and a function within that controller is def getRandomInfo, so django allows two ways to access this endpoint, either via the url r'^random/getRandomInfo/$ (yes regex is allowed here) or via the name as stated in the example here.
Best of Luck :)

Related

How to add custom Header in Authlib on Django

I would need some of your help adapting Authlib with Django.
I'm trying to develop a Django app using OpenId and Authlib to connect my users and facing an issue with the access token, the issue invalid_client occurs. Using Postman I found out that the OpenId provider needs some parameters in the Header like 'Content-Length' or 'Host'.
When the Header param is defined in client.py, it works like a charm. However, I'd like to pass the custom header from views.py (mostly to avoid defining the Host directly in the package), but authorize_access_token doesn't allow multiple arguments,
def auth(request):
token = oauth.customprovider.authorize_access_token(request)
Maybe the "Compliance Fix for non Standard" feature might help, but I wasn't able to adapt it for Django and the Header parameter
https://docs.authlib.org/en/stable/client/oauth2.html#compliance-fix-oauth2
from authlib.common.urls import add_params_to_uri, url_decode
def _non_compliant_param_name(url, headers, data):
params = {'site': 'stackoverflow'}
url = add_params_to_uri(url, params)
return url, headers, body
def _fix_token_response(resp):
data = dict(url_decode(resp.text))
data['token_type'] = 'Bearer'
data['expires_in'] = int(data['expires'])
resp.json = lambda: data
return resp
session.register_compliance_hook(
'protected_request', _non_compliant_param_name)
session.register_compliance_hook(
'access_token_response', _fix_token_response)
Does anyone know a way to pass a custom Header to Authlib or defining it using the Compliance Fix and Django?
I had to do this recently for a provider that required an Authorization header added to the the refresh token. Here is the code I used.
Add the register_compliance_hook inside the function that is called using the compliance_fix argument when initializing the service.
def _compliance_fixes(session):
def _add_header_refresh(url, headers, body):
headers.update({'Authorization': "Basic " + self.secret_client_key})
return url, headers, body
session.register_compliance_hook('refresh_token_request', _add_header_refresh)
oauth = OAuth()
oauth.register("oauth-service", compliance_fix=_compliance_fixes)

Is it possible to develop an app using the remove.bg API in Flutter?

I got an API called remove.bg . I want to use this API ( provided in python language ) in my Flutter App. Is it even possible?
This API uses for removing image background.
What are the steps/ research I need to do to get this thing working?
Do lots of Googling, but ends up with nothing.
Really Appreciate your help!!!
OR can I use this link and able to upload and get the output in my app?
for example, I open the APP, and it will show two-button -> Upload image & download image.
when user clicks the Upload button it will redirect to this link and after processing done in the website, the output we can able to download in our app.
This is possible with Flutter's http package. Assuming it is some form of RESTful API this should give you a starting point:
final body = {"image_file": "#/path/to/file.jpg", "size": "auto"};
final headers = {"X-API-Key": INSERT_YOUR_API_KEY_HERE};
final response = await http.post('https://api.remove.bg/v1.0/removebg',
body: body,
headers: headers);
if (response.statusCode == 200) {
// do something with response.body
} else {
throw Exception('Failed to do network requests: Error Code: ${response.statusCode}\nBody: ${response.body}');
}
A good tutorial on http in Flutter is here.
Note: You may have to do json.encode(body) and the same with header and use json.decode(response.body) depending on the API.
Hope it helps, and if so please up vote and accept as answer and if not please leave a comment below.

Using return vales from flask in ios application

I was trying to use flask as a backend for my iOs application. Currently it seems to be working, and the backend is hosted on heroku. The flask backend looks a little like this:
#app.route('/get_token', methods=['POST'])
def create_token():
token = make_token()
return token
I can run this function and confirm that it runs using a snippet like this with swift (using alamofire):
let url = "https://my-backend.herokuapp.com/get_token"
Alamofire.request(url, method: .post, parameters: nil, encoding: JSONEncoding.default)
And that runs fine. But now I want to do something (specifically save the token from flask) with the return value from flask. But I am confused as to how to do this. Any suggestions?
I would return a JSON response from Flask, and then you can easily parse that JSON object however you choose in your iOS app. Flask has a built in method, jsonify, which makes it easy to create a JSON responses.
You response would look like return jsonify(token=token)
Parse JSON with Alamofire:
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
//to get status code
if let status = response.response?.statusCode {
switch(status){
case 201:
print("example success")
default:
print("error with response status: \(status)")
}
}
//to get JSON return value
if let result = response.result.value {
let JSON = result as! NSDictionary
print(JSON)
}
}
Source: https://stackoverflow.com/a/33022923/6685140

To implement a web socket feature with Flask-Restful (REST Api) on the server side

WORK DONE: I have implemented a REST API with Mongo DB (PyMongo driver) using Flask-Restful having one endpoint named “Users” consisting of GET, POST, PUT, DELETE
My PUT method:
def put(self, short_name ):
coll = db.users
user_info = request.get_json()
print user_info #for debugging
coll.update({'short_name': short_name'}, {"$set": user _info})
return Response(json_util.dumps(user _info), mimetype='application/json')
The above PUT method accepts a short_name, updates the User database and returns a response.
Work to be done: I need to implement a server side web socket feature where after coll.update({'short_name': short_name'}, {"$set": user _info}) is executed, a message to the client (i.e frontend which is built completely on angular) has to be sent stating “Data updated successfully”.
I saw a couple of snippets online but couldn’t find one with REST Api. For now I only require the server side implementation. I will try to figure out the client side implementation later.
Any help on how to accomplish this is appreciated. Can it be done with simple python or is socket.io needed. All solutions are welcome.
EDIT: My modified server code
def put(self, short_name ):
coll = db.users
user_info = request.get_json()
print user_info #for debugging
coll.update({'short_name': short_name'}, {"$set": user _info})
emit('my response', {'data': 'update successful'})
return Response(json_util.dumps(user _info), mimetype='application/json')
Added this on the client side:
namespace = '/';
var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
socket.on('my response', function(msg) {
console.log(msg.data)
});
Now when I run my application, the console on the client side does not print my data sent from the server. Can anyone explain where am I going wrong.
This should be interesting... Flask or Django or similar frameworks are built to serve HTTP request based method.
Imagine
user click the button
Your framework take the request
do the needs
and finally return the response
This is the actual flow of web server. but in your case you may want to update the frontend when DB updated or Any event changes.. In this case you need Socket to communicate with frontend.
Features of web sockets
Communicate with your website whenever you need.
Just put the javascript in the html page like this
$(document).ready(function(){
var socket = io.connect('http://localhost:8000/test');
});
And now you are connected with Website so next in your python code..
#socketio.on('my event', namespace='/test')
def test_message(message):
emit('my response', {'data': message['data']})
just like this import emit and put your message and you are good to go. For more detail please look here http://flask-socketio.readthedocs.org/en/latest/

Responding to AJAX GET and POST requests with Google App Engine (Python)

I have confusion on how the servers(here app engine) respond to AJAX GET and POST requests. I want send a GET request to my server and get some JSON data back.
Here is the AJAX GET request
function syncRestoreLinks(e) {
var request = new XMLHttpRequest();
var url = "/sync"
request.open("GET", url);
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange = function() {
if (request.readyState === 4) {
console.log(request.responseText);
}
}
request.send(null);
console.log("Getting links from db");
}
Handler on the server side
class SyncHandler(Handler):
def get(self):
response_data = {"loggedIn":False, "linkData":None, "success":False}
json_txt = json.dumps(response_data)
self.response.headers['Content-Type'] = 'application/json; charset=UTF-8'
self.response.out.write(json_txt)
def post(self):
response_data = {"loggedIn":False, "linkData":None, "success":False}
json_txt = json.dumps(response_data)
self.response.headers['Content-Type'] = 'application/json; charset=UTF-8'
self.response.out.write(json_txt)
This handler writes my response data out to the screen where as I want it to send it back and let JS handle it. (I am able to use server redirects here.)
If I make a POST request instead, the code works the way I intend it to. But here, I cannot make server redirects or render pages and only the script making request has that control.
Is this how GET/POST responses work or I am doing something stupid in my code?
Is there any way for GET response not to be written on the page and be sent to JS? In the code above the responseText is an empty string but, the json is printed on screen.
I'm doing AJAX Get requests successfully with app engine right now.
Your sync handler looks correct. Are you sure it is being called? Add a logging.info() statement there to make sure. If it is being called, then I suspect the error is on the front end. I use jQuery and not XMLHttpRequest so I can't you help you with that. My jQuery call looks like this:
$.get(url, callback_function, 'json');
You can add a POST handler to your SyncHandler like this:
def post(self):
...
self.response.out.write(json_txt)
The strange part is that your POST request should not be working without this code to handle the request. You only show a get() method in your code.

Categories