I use vue.js to build a frontend and run it on http://localhost:8080 with npm run dev to develop.
And I use flask to build a backend and run it on http://localhost:8081.
I also set the crossdomain decorator for my route in Flask:
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
#app.route("/api", methods=['POST', 'OPTIONS'])
#crossdomain(origin="*")
def test():
return "hello world"
Then I send a POST request by vue-resource to the backend:
this.$http.post("http://localhost:8081/api", "somedata").then({}, {})
No surprisingly, the browser send an OPTIONS request.
So my questions are:
Now that the server side has allow crossdomain, can I send POST request directly by vue-resource?
If not, must I use CORS from flask_cors?
Is there any way that I can run frontend and backend both on 8080 port, which can prevents from crossdomain problem?
Well, I haven't seen all your front-end code, but I do wonder if you've set the Vue.http.headers?
you can, on the front end, set your common headers like this:
Vue.http.headers.common['Access-Control-Allow-Origin'] = value;
More information here:
CORS issue with Vue.js
EDIT: Did this solve your question?
Related
Trying to convert from python request to chilkat2.HttpRequest :
import requests
data = {"username": "user","password": "pass","remember": "on"}
sign_in_url = 'https://www.tradingview.com/accounts/signin/'
signin_headers = {'Referer': 'https://www.tradingview.com'}
response = requests.post(url=sign_in_url, data=data, headers=signin_headers)
token = response.json()['user']['auth_token']
P.S. Cause no right username and password - will return status_code:200
b'{"error":"Invalid username or password","code":"invalid_credentials"}'
I have this:
http = chilkat2.Http()
req = chilkat2.HttpRequest()
req.AddParam("username","user")
req.AddParam("password","pass")
req.AddParam("remember","on")
req.Path = '/accounts/signin/'
req.HttpVerb = "POST"
http.FollowRedirects = True
http.SendCookies = True
http.SaveCookies = True
http.CookieDir = "memory"
resp = http.SynchronousRequest('www.tradingview.com',443,True,req)
print(http.LastErrorText)
But response - statusCode: 403 Forbidden
What am I doing wrong?
See the tradingview.com API documentation: https://www.tradingview.com/rest-api-spec/#section/Authentication
You can see that an application/x-www-form-urlencoded POST is required.
It's easy to do with Chilkat. See this documentation showing how to send common HTTP request types: https://www.chilkatsoft.com/http_tutorial.asp
You'll want to send a request like this: https://www.chilkatsoft.com/http_post_url_encoded.asp
I have the following 2 views and on a specific param I need to send a PATCH request to another view on receiving certain params. However i get the following error, how to rectify this?
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view,
but received a `<class 'requests.models.Response'>`
The view are as follows:
class Emp_Status_Trans_ListView(APIView):
permission_classes = [DjangoCustomModelPermissions]
queryset = Emp_Status_Trans.objects.none()
def get(self, request, format=None):
emp_mast_id=request.query_params.get('employee',None)
linked_model_data = [("hr","Emp_Status_Mast","Emp_Status_Mast_Serializer",("emp_status_mast_id","emp_status_short"))]
final_resp = {}
db_data = Emp_Status_Trans.objects.all().prefetch_related("emp_mast","emp_status_mast")
if emp_mast_id:
db_data = db_data.filter(emp_mast=emp_mast_id)
serializer = Emp_Status_Trans_Serializer(db_data, many=True)
final_resp['emp_status_trans'] = serializer.data
get_linked_data(final_resp, linked_model_data)
return Response(final_resp)
def post(self, request, format=None):
patch_emp_mast=request.query_params.get('patch_emp_mast',None)
serializer = Emp_Status_Trans_Serializer(data=request.data)
if serializer.is_valid():
serializer.save()
if patch_emp_mast:
return self.patch_emp_mast(serializer.data,request.META.get("HTTP_HOST"),request.META.get("HTTP_AUTHORIZATION"))
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def patch_emp_mast(self,data,domain,access_token):
url = "http://"+domain+"/hr/emp_mast/"+str(data['emp_mast']['id'])+"/"
headers = {'Content-Type': 'application/json', 'Authorization':access_token}
data = {
'emp_status_mast': data['emp_status_mast'],
}
return requests.patch(url,headers=headers, data=json.dumps(data))
patch_emp_mast is called when query param is received however it fails with the error mentioned earlier. How to rectify this?
you can rewrite your code like ;
def patch_emp_mast(self,data,domain,access_token):
url = "http://"+domain+"/hr/emp_mast/"+str(data['emp_mast']['id'])+"/"
headers = {'Content-Type': 'application/json', 'Authorization':access_token}
data = {
'emp_status_mast': data['emp_status_mast'],
}
try:
response= requests.patch(url,headers=headers, data=json.dumps(data))
return Response("status":True,"response":response.json())
expect:
return Response("status":False,"response":{})
Best regards
I have a Django Rest API that sets the cookie in a response object. When I hit my browsable API, the browser stores the cookie under Application>Cookies. When I try to reproduce the same result using an AJAX call, the cookie isn't stored automatically; although I do get a response object in AJAX call.
My code is as follows
views.py
class UserLogin(generics.GenericAPIView):
serializer_class = serializers.UserLoginSerializer
permission_classes = (
permissions.AllowAny,
)
def finalize_response(self, request, *args, **kwargs):
"""
Set Authorization in cookie.
"""
response_obj = super(UserLogin, self).finalize_response(
request, *args, **kwargs)
if request.POST and response_obj.status_code == 200:
response_obj['Authorization'] = 'Token '\
+ response_obj.data['auth_token']
print 'COOKIE NOT SET'
response_obj.set_cookie(
'Authorization', response_obj['Authorization'])
print 'COOKIE SET'
return response_obj
def post(self, request):
"""
If serializer is valid.
- call action.
"""
serializer = self.get_serializer(
data=request.data)
if serializer.is_valid():
user = serializer.validated_data.get('user')
token, boolean = Token.objects.get_or_create(user=user)
if not boolean:
token.created = datetime.datetime.now()
token.save()
# user.login_attempts = 0
user.save()
data = serializers.TokenSerializer(token).data
return response.Response(
data=data,
status=status.HTTP_200_OK,)
return response.Response(
data=serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
serializers.py
class UserLoginSerializer(serializers.Serializer):
def __init__(self, *args, **kwargs):
super(UserLoginSerializer, self).__init__(*args, **kwargs)
self.user = None
self.fields[User.USERNAME_FIELD] = serializers.CharField()
password = serializers.CharField(
style={'input_type': 'password'})
def validate(self, data):
username = data.get(User.USERNAME_FIELD).lower()
password = data.get('password')
try:
user = User.objects.get(username=username)
except:
raise serializers.ValidationError(
messages.INVALID_CREDENTIALS_ERROR)
data['user'] = user
user_service = UserService()
is_valid = user_service.verify_account(user, password)
if not is_valid:
raise serializers.ValidationError(
messages.INACTIVE_ACCOUNT_ERROR)
return data
class Meta:
fields = (User.USERNAME_FIELD, 'password')
ajax call
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'username' : $('input[name=username]').val(),
'password' : $('input[name=password]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : 'http://13.232.122.165/users/login/',
data : formData,
dataType : 'json',
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
location.href = "localhost:5000/profile"
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
The cookie is being attached but you can't see it from developer tools unless you're on the request url domain.
Try logging in using ajax and hitting the request url (any end point) on browser, you'll see the cookie.
As you know, some captchas are generating using user session, and i must to somehow save to computer this image, for testing our app, but how, and what better to choise?
For example on http::get i have such code, with cookies:
http = Net::HTTP.new('***', 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
path = '****'
# GET request -> so the host can set his cookies
resp, data = http.get(path)
body_text = resp.body
#puts "Body = #{body_text}"
cookie = resp.response['set-cookie'].split('; ')[0]
#captcha_url = (/BotDetectCaptcha.ashx?get=image&c=***;t=(.*)" \/>/.match body_text)
# POST request -> logging in
puts "captcha_url = #{#captcha_url}"
data = 'BotDetectCaptcha.ashx?get=image&c=****&t=#{#captcha_url}'
headers = {
'Cookie' => cookie,
'Referer' => '****',
'Content-Type' => 'image-jpeg'
}
resp, data = http.post(path, data, headers)
so, perhaps, i have image that i need, but! how can i save it? All google'd articles say me, that i must use open-uri, but how to be, when i have to use session also? Maybe i could do it somehow with http class from ruby?
So how can i download image from loaded page, or via url?
You can get image to variable and save it:
IMG_PATH = '/var/www/pics/'
Class Img
def self.download(data, filename)
open(IMG_PATH + filename, 'wb') do |file|
file << open(data).read
end
return true
end
end
img = Img.download(data, filename)
I am writing unittests for django views. I have observed that one of my views returns redirection code 301, which is not expected.
Here is my views.py mentioned earlier.
def index(request):
return render(request, 'index.html',
{'form': QueryForm()})
def query(request):
if request.is_ajax():
form = QueryForm(request.POST)
return HttpResponse('valid')
Below is urls.py.
urlpatterns = patterns('',
url(r'^$', 'core.views.index'),
url(r'^query/$', 'core.views.query')
)
And unittest that will fail.
def so_test(self):
response = self.client.post('/')
self.assertEquals(response.status_code, 200)
response = self.client.post('/query', {})
self.assertEquals(response.status_code, 200)
My question is: why there is status 301 returned?
You have defined a url that matches /query/, but you are testing /query. Django is redirecting to the url with the trailing slash because APPEND_SLASH=True in your settings.
You probably want to change your test to:
response = self.client.post('/query/', {})
For me, the problem was that I mistakenly ran the tests with a setting.py file that had SECURE_SSL_REDIRECT = True. Changing to SECURE_SSL_REDIRECT = False solved the issue.
Another option is to use the client with secure=True, i.e.:
response = self.client.post('/query/', {}, secure=True)
which will make the client emulate an HTTPS request.