So basically I have an "/add" route where it is used to manually seed in test user data to mongodb and I want to be able to pass that user's ID to the URL for the route "/agreement" so when the user is on the agreement page, their "_id" will be mapped to that URI and the info they enter on the agreement page will update their data that we seeded in the "/add" route.
#app.route('/add')
def add():
users = mongo.db.users
users.insert({
"_id" : "autogenID",
"_comment" : " File structure for files in client collection",
"client_name" : "Name_of_firm",
"contact_name" : "Name_of_contact",
"contact_email" : "Email_ID_of_contact",
"contact_password" : "passowrd_encryped_bcrypt",
"client_industry" : "client_industry",
"monthly_checks_processed": "monthly_checks_processed",
"parent_id" : "client_id",
"child_id" : [{
"child_id": "client_id",
"child_id": "client_id"
}],
"agreement_authorised" : "boolean_yes_no",
"agreement" : "agreement_text",
"client_card" : [{
"name_on_card": "client_name",
"credit_card_number": "credit_card_number_bycrypt",
"expiration_date" : "expiration_date_bycrypt",
"credit_card_cvc" : "credit_card_cvc_bycrypt",
"active" : "boolean_yes_no"
}]
})
all_users = users.find()
for user in all_users:
print user
#app.route('/agreement', methods=['GET', 'POST'])
def agreenment(id):
user = mongo.db.users.find("_id")
print user
return render_template('agreement.html', user=user)
I think the issue lies in the agreement resource where maybe I should write /agreement/<id> but I think I am missing a fundamental understanding of where the <id> is instantiated. I also don't completely understand what the function of the agreement parameter is but I put (id) because this seems like something I would have to do in order to get the user's info passed to another resource.
I also think user = mongo.db.users.find("_id") might not be correct as well as return render_template('agreement.html', user=user). Part of me thinks that maybe I should do redirect instead of render but if anyone can lend a hand I would greatly appreciate it.
Try this:
#app.route('/agreement/<user_id>', methods=['GET', 'POST'])
def agreement(user_id):
user = mongo.db.users.find_one({"_id": user_id})
print user
return render_template('agreement.html', user=user)
URL parameter names in Flask are specified in the route parameter, and they have to match the decorated function's signature.
Querying in Mongo is done by passing a dict specifying the constraints, so db.users.find_one({"_id": user_id}) will return a single result with _id matching the user_id variable.
Edit: Actually, as per the documentation, you can just do:
db.users.find_one(user_id).
Related
I'm trying to update contacts using Python and Microsoft Graph within a profile page I've created using Django.
I can access contacts and get all the data I need, however I can't work out how to update the fields.
The only information I can find is on the Graph website, however I can't work out how to translate this into usable code:
PATCH PATCH https://graph.microsoft.com/beta/me/contacts/
Content-type: application/json
{
"title": "Mr",
"givenName": "Steve"
}
I assume there is a way to just put this together as a simple link but I cannot work it out. I've tried the following:
PATCH https://graph.microsoft.com/beta/me/contacts/{id}/title/Mr
PATCH https://graph.microsoft.com/beta/me/contacts/{id}/title:Mr
PATCH https://graph.microsoft.com/beta/me/contacts/{id}/title/$value==Mr
but they all produce errors
There are no tutorials for doing this with Python on the Microsoft site and it's proving very difficult to find any info on it. So hopefully someone can help out.
Cheers!
!!!!!!!!!!!!! UPDATE !!!!!!!!!!!!!!!!!!
Here is my current code which still sadly does nothing:
In my views.py:
def profile(request):
if request.session['has_id']==False:
contact_id = request.session['contact_id'] = request.POST.get('edit')
request.session['has_id'] = True
else:
contact_id = request.session['contact_id']
context = ct.profile(request,id=request.session.get('contact_id'),init=initialize_context,get_tok=get_token)
if request.method=="PATCH":
ct.update(contact_id,'title',request.PATCH.get('title'))
return render(request, 'tutorial/profile.html', context)
and my updater:
def update(id,key,value):
url = '{}/me/contacts/{}'.format(graph_url,id)
payload = {key : value}
head = {
"Content-type" : "application/json",
}
requests.patch(url=url,data=payload,headers=head)
Finally worked it out, I thought I'd tried something like this yesterday but apparently not.
Here's how to do it!
views.py
def profile(request):
if request.session['has_id']==False:
contact_id = request.session['contact_id'] = request.POST.get('edit')
request.session['has_id'] = True
else:
contact_id = request.session['contact_id']
context = ct.profile(request,id=request.session.get('contact_id'),init=initialize_context,get_tok=get_token)
if request.method=="PATCH":
ct.update(contact_id,'title',request.PATCH.get('title'))
return render(request, 'tutorial/profile.html', context)
contacts_helper.py:
def update(token,id,key,value):
graph_client = OAuth2Session(token=token)
url = '{}/me/contacts/{}'.format(graph_url,id)
payload = {key : value}
graph_client.patch(url,data=json.dumps(payload),headers={'Content-type': 'application/json'})
Obviously if you're looking at this you've probably already set up auth_helper.py and graph_helper.py but if you haven't then you should head over the Microsoft Graph website and follow these instructions:
https://developer.microsoft.com/en-us/graph/get-started/python
How to get 'jti', not mine but by the "username" ?
On registration/login jti for access and refresh were assigned to 'username'.
All instructions and docs note only how to get my own jti to logout with smth. like this code:
class UserLogoutRefresh(Resource):
#jwt_refresh_token_required
def post(self):
jti = get_raw_jwt()['jti']
try:
revoked_token = RevokedTokenModel(jti = jti)
revoked_token.add()
return {'message': 'Refresh token has been revoked'},200
except:
return {'message': 'Something went wrong'}, 500
How to get jti for another user.
I suppose smth like:
jti = get_raw_jwt(identity='someusername')['jti']
has to exist for this, who knows ???
Each token will have a unique jti, it’s not scoped per username. If the same user creates 3 tokens, all of them will have a different jti for example. If you want to have access to these jti then you will use the decode_token function when you create your token and save it in a datastore somewhere you can look it up later
I need to pass session id in URL query string after login using Django and Python but in my case I am getting some error. My code is below.
def loginsave(request):
"""This function helps to login the user """
if request.method == 'POST':
password = request.POST.get('pass')
uname = request.POST.get('uname')
per = User.objects.all().filter(
Q(password__icontains=password) & Q(uname__icontains=uname)).count()
if per > 0:
user = User.objects.filter(
Q(password__icontains=password) & Q(uname__icontains=uname))
for use in user:
uid = use.id
user_name = use.uname
request.session['id'] = uid
request.session['sess'] = dict(dt=str(datetime.now()),
value='session')
request.session['sess_id'] = 'abcd1234'
return render(request, 'bookingservice/home.html',
{'count': per, 'username': user_name})
else:
return render(request, 'bookingservice/login.html', {})
This is my login function here I am creating session id and I need to pass it over URL. My menu list is given below.
Home
Add Booking
Add Personal Info
I am doing like this but here I am getting the following error.
Exception Value:
Could not parse the remainder: '["sess_id"]' from 'request.session["sess_id"]'
Here I need after login the session id should come over every page URL.
Change
{{request.session["sess_id"]}}
to
{{ request.session.sess_id }}
usually the template language of django works this way. Here a dot in a variable name signifies a lookup.When the template system encounters a dot in a variable name, it tries the following lookups, in this order:
Dictionary lookup. Example: request.session["bar"]
Attribute lookup. Example: request.session.bar
List-index lookup. Example: request.session[bar]
You can find more at docs
You have an error in template, it should read (mind the quotes):
Home
Add Booking
Add Personal Info
I'm using pymongo and flask to put information about which desktops a person owns from a database onto a webpage in a table. Simple enough. But I have a button which is supposed to remove a desktop from the database using $pull.
The mongo document looks like this:
{
"_id" : ObjectId("55c4a89a80071a0ef20e4df1"),
"Hostname" : "XXXXXXXXX",
"BUILD OS" : "WINDOWS 7 ENTERPRISE",
"Current User" : "CAMPELK",
"Primary User" : "CAMPELK",
"Location" : "XXXXX",
"Model" : "vmware inc. vmware virtual platform",
"BUILD Version Full" : "5.1.00.00",
"BUILD Version" : 5.1,
}
(I've had to censor some data due to workplace rules)
The name of the desktop model is returned from a drop down menu form as a string like this:
#app.route('/contact_desktop', methods=['GET', 'POST'])
def contact2():
form1= name_search()
name = form1.name.data
choices = DI.make_dictionary()
form2 = ContactFormDesktop()
models = DI.return_model(name)
if request.method == 'POST':
DI.remove_give_back_desktop(models, form2.choose_desktop.data, name)
return render_template('thanks.html', thing = "desktop")
And the remove_give_back_desktop() method is supposed to remove the field which matches the model string returned by the form:
def return_model(name):
models = list()
for entry in db.names.find({}):
model = entry["models"]
models.append(model)
return models
def remove_give_back_desktop(model1, model2, name):
for entry in model1:
if entry == model2:
db.desktops.update_one({"Current User":name, "Model": entry},{"$unset":{"Model":""}})
However, nothing is happening when I click the button in the html page, no errors are thrown and the code runs just fine otherwise, but the field that was supposed to be removed is still there.
The update $unset method works in the mongo terminal when I manually insert the name and model, so is my syntax wrong for pymongo or is there a deeper problem?
Thanks!
I am making a stock application, where, after a user types in a stock such as MSFT, they are redirected to .../stock?s=MSFT I have successfully made this part, but now I need Python to grab this current, unique URL so that I can parse the quote (in this case, the MSFT) out if it and save it as a new variable.
The easiest way I can think of is just to get the current URL, although I cannot seem to find a way to do this; using self.request... but this returned the error:
NameError: global name 'self' is not defined
The other ideas I came across was to use a form of urllib as it contains a specific .request_qs() method, although this requires me to pass the URL as a parameter, which should be unique every time because of the change in stock.
Here is the Python I currently have:
#app.route('/', methods=['GET', 'POST'])
def home_search():
if request.method == 'POST':
st = request.form['s']
return redirect(url_for('stock')+'?s='+st)
return render_template('stk.html')
#app.route('/stock', methods=['GET', 'POST'])
def stock():
#here I need to save the variable 'name' as the current URL. I can parse it later.
url="http://finance.yahoo.com/d/quotes.csv?s="+name"&f=snl1"
text=urllib2.urlopen(url).read()
return render_template('stock.html')
Many thanks in advance.
It's request (imported from the flask package), not self.request
The Flask docs have, as always, thorough documentation about variables in the URL: http://flask.pocoo.org/docs/quickstart/#variable-rules
#app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
On that occasion, you should read the whole Quickstart from the Flask docs: http://flask.pocoo.org/docs/quickstart/
You haven't posted any info on where the error occurs :) And I can't see where you're trying to access self.requests.
Looking at other Flask apps, it seems you should just access request instead.
Take a look at these examples: https://github.com/mitsuhiko/flask/tree/master/examples