How to retrieve user object using PostMan to test my endpoints - sqlite

Users can create and maintain their profiles rather than enter in
their information each time they order
API Actions:
Retrieve a User Object and its fields by their username
Update the user and any of their fields except for mail
This is my code below:
views.py
"""api views inlcude method: customer list, """
#csrf allows for post without auth
#csrf_exempt
def List_All_Customers(request):
customer = Customer.objects.all()
#returns all the customer from db
if request.method == 'GET':
serializer = CustomerSerializer(customer, many=True)
return JsonResponse(serializer.data, status= 200, safe=False)
#add new customer in the db
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = CustomerSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
#csrf_exempt
def Customer_detail(customer):
#check if the customer with the given name is in the database
try:
customer = Customer.objects.filter(name = name)
#if not in database, throw 400 error
except Customer.DoesNotExist:
return HttpResponse(status = 404)
#if customer exists with the given name and is a get method, return that name object
if request.method == 'GET':
serializer = CustomerSerializer(customer)
return JsonResponse(serializer.data)
#delete method will delete the customer with a specific name
elif request.method == 'DELETE':
Customer.objects.filter(name = name).delete()
return HttpResponse(status=204)
#csrf_exempt
def get_current_user(request):
if request.method == 'POST':
customer = request.POST.get('name')
customer = authenticate(user=user)
if customer:
if customer.is_authenticated:
signBool = signatureAuth(username)
if signBool == 'AUTHENTICATED':
login(request, customer, backend=settings.AUTHENTICATION_BACKEND[0])
return JsonResponse(serializer.data)
'''
return JsonResponse({
'user':customer.user,
'name':customer.name,
'email':customer.email,
})
'''
model.py
class Customer(models.Model):
user=models.CharField(max_length=200,null=True)
name=models.CharField(max_length=200,null=True)
email=models.CharField(max_length=200,null=True)
password=models.CharField(max_length=200,null=True)
card_info=models.CharField(max_length=200,null=True)
def __str__(self):
return str(self.Customer)

Related

I am not able to add form entries to my database

Problem
I am trying to push username and password entries to my database using following code(named as application.py inside my project)
Code
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
application = Flask(__name__)
application.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydtb.db'
db = SQLAlchemy(application)
class Mydtb(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement = True)
user = db.Column(db.String(50), nullable = False)
password = db.Column(db.String(20), nullable = False)
created = db.Column(db.DateTime, default = datetime.utcnow)
def __init__(self, user, password):
user = self.user
password = self.password
#application.route('/', methods=['POST', 'GET'])
def home():
title = 'Registration page'
if request.method == 'POST':
record = Mydtb(request.form['usrname'], request.form['pwd'])
db.session.add(record)
db.session.commit()
return redirect('/')
else:
mydtb = Mydtb.query.order_by(Mydtb.created)
return render_template('index.html', title=title, mydtb = mydtb)
if __name__ == '__main__':
application.run(debug = True)
I've already generated .db file, html form is also working fine but it seems application.py code is unable to push those form entries to database.
You can see the error that I am getting from debug section , I want to fix it without using extra libraries.

Flask db.Column(db.Boolean) not updating for email confirmation

i am trying to update a db column but it's not working for some reason, the boolean value is not changing to True. in database it is always False even when i confirm the email try token.
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer(),primary_key=True)
name = db.Column(db.String)
email = db.Column(db.String)
password = db.Column(db.Integer)
date_added = db.Column(db.DateTime)
confirmed_email = db.Column(db.Boolean, nullable=True, default=False)
def __init__(self,name,email,password,date_added):
self.name = name
self.email = email
self.password = password
self.date_added = date_added
and this is my route for token
#app.route('/confirm_email/<token>')
def confirm_email(token):
try:
email = serializer.loads(token, salt='true', max_age=250)
except SignatureExpired:
return 'The token is expired for'
user = User.query.filter_by(email=email).first()
user.confirmed_email = True
db.session.add(user) #<-- i tried also without this line
db.session.commit()
return redirect(url_for('index'))

Script to create new Folder in Alfresco repository

I want to create a script who allow me to create a new folder in Alfresco repository, but i haven't any idea to how achieve this.
Is there anyone who can tell me how to manage this.
Sorry for not posting any code, because i'm very new to alfresco and i haven't idea how to manage this.
The best way to create a folder (or perform other CRUD functions) remotely, such as from a command line program, is to use CMIS. There are a number of CMIS client implementations depending on what language you'd like to use. These are managed at the Apache Chemistry project.
Here is an example that uses cmislib, a Python CMIS client, to create a folder:
from cmislib.model import CmisClient
from cmislib.browser.binding import BrowserBinding
client = CmisClient('http://localhost:8080/alfresco/api/-default-/cmis/versions/1.1/browser', 'admin', 'admin', binding=BrowserBinding())
repo = client.defaultRepository
folder = repo.getObjectByPath("/User Homes")
createdFolder = folder.createFolder("another test folder")
print "Done, created: %s" % createdFolder.id
Here is an example that uses OpenCMIS, a Java implementation, from Groovy:
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1')
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-commons-api", version="0.13.0")
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-commons-impl", version="0.13.0")
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-client-api", version="0.13.0")
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-client-impl", version="0.13.0")
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-client-bindings", version="0.13.0")
import org.apache.chemistry.opencmis.commons.*;
import org.apache.chemistry.opencmis.commons.enums.*;
import org.apache.chemistry.opencmis.client.*;
import org.apache.chemistry.opencmis.client.api.*;
import org.apache.chemistry.opencmis.client.runtime.*;
import org.apache.chemistry.opencmis.commons.data.*;
import org.apache.chemistry.opencmis.commons.impl.dataobjects.*;
import org.apache.chemistry.opencmis.commons.exceptions.*;
import java.nio.file.Paths
import groovy.json.JsonOutput
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import java.text.NumberFormat;
def ALF_SERVICE = '/alfresco/s'
def CMIS_SERVICE = '/alfresco/api/-default-/public/cmis/versions/1.1/browser'
final BindingType CMIS_BINDING = BindingType.BROWSER;
// Get options
def url = System.console().readLine('Alfresco server URL [http://localhost:8080]: ')
if (url == null || url == '') url = "http://localhost:8080"
def folderPath = System.console().readLine('Folder path [/User Homes]: ')
if (folderPath == null || folderPath == '') folderPath = "/User Homes"
def folderName = System.console().readLine('Folder name to create: ')
def userName = System.console().readLine('Your username: ')
def password = System.console().readPassword('Your password: ')
println 'WARNING: About to modify folders on ' + url + ' as ' + userName + '.'
def confirm = System.console().readLine('Are you sure (Y/N): ')
if (confirm.toLowerCase() != 'y' && confirm.toLowerCase() != 'yes') {
println "Quitting"
System.exit(0)
}
// Login to Alfresco
def client = new RESTClient(url)
def resp = client.get(path : ALF_SERVICE + '/api/login', query: ['u': userName, 'pw': password.toString(), 'format': 'json'])
assert resp.status == 200
def ticket = resp.data.data.ticket
println "Successfully logged in to Alfresco..."
// Leave the username as an empty string to auth with a ticket
Session session = createCMISSession(url + CMIS_SERVICE, CMIS_BINDING, "", ticket);
Folder folder = findFolder(session, folderPath)
if (folder == null) {
println "ERROR: Could not find: " + folderPath
System.exit(0)
}
println "Found: " + folder.name + " (" + folder.id + ")"
Map<String,String> newFolderProps = new HashMap<String, String>()
newFolderProps.put("cmis:objectTypeId", "cmis:folder");
newFolderProps.put("cmis:name", folderName);
Folder createdFolder = folder.createFolder(newFolderProps)
println "Done, created: " + createdFolder.id
Session createCMISSession(final String cmisEndpointUrl,
final BindingType cmisBinding,
final String cmisUser,
final String cmisPassword) {
SessionFactory sf = SessionFactoryImpl.newInstance();
Session result = null;
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(SessionParameter.BINDING_TYPE, cmisBinding.value());
parameters.put(SessionParameter.BROWSER_URL, cmisEndpointUrl);
parameters.put(SessionParameter.USER, cmisUser);
parameters.put(SessionParameter.PASSWORD, cmisPassword);
// Note: grabbing the first repository may not work as expected on multi-tenant Alfresco (most notably Cloud)
result = sf.getRepositories(parameters).get(0).createSession();
return (result);
}
Folder findFolder(Session session, String folderPath) {
Folder result = null;
try {
CmisObject folder = session.getObjectByPath(folderPath);
if (folder != null &&
BaseTypeId.CMIS_FOLDER.equals(folder.getBaseTypeId())) {
result = (Folder) folder;
}
} catch (CmisObjectNotFoundException confe) {
// Swallow and move on - we return null in this case
println "ERROR: getObjectByPath threw a CmisObjectNotFoundException"
}
return (result);
}
In the Groovy example, I am logging in and getting a ticket so that I can make both CMIS and non-CMIS calls, although I am not showing any non-CMIS calls in this example.
var nodeNew = parentNode.createFolder("Name of folder");
Above code will create folder using alfresco javascript.parentNode is an object of Node.
Below link have some more details on it.
https://community.alfresco.com/thread/166358-webscript-to-create-folder-space

Transaction never finished Neo4j

I have a method which should create a sub-graph defined this way:
#Transactional
public Post createAndLink(Appuser appuser, Post post, String linkTo) {
Post savedPost = null;
if(post != null && appuser != null){
post.setCreatedBy(appuser);
if(post.getId() == null && post.getId() == ""){
post.setId("IND"+GenerateUUID.getUUID());
}
System.out.println(">>> Id created : "+post.getId());
//Date check
String d = post.getDate();
if(d != null && d.length() == 11 && ConversionUtils.isNumeric(d.substring(0, 4))
&& ConversionUtils.isNumeric(d.substring(5, 7)) && ConversionUtils.isNumeric(d.substring(8, 10))){
if(!ConversionUtils.isPastDate(d)){
System.out.println("Cannot save post with date after today");
return null;
}
}
System.out.println(">>> Date created : "+post.getDate());
//People check
Set<People> people = new HashSet<People>();
if(post.getPeople() != null){
for(People p : post.getPeople()){
People pFromDb = peopleService.findById(p.getId());
people.add(pFromDb != null ? pFromDb : new People("PPL"+GenerateUUID.getUUID(), p.getName()));
}
post.setPeople(people);
}
System.out.println(">>> People created : "+post.getPeople());
//Place check
if(post.getPlace() != null){
Place pFromDb = placeService.findById(post.getPlace().getId());
post.setPlace(pFromDb != null ? pFromDb : new Place(post.getPlace().getId()));
}
System.out.println(">>> Place created : "+post.getPlace());
System.out.println("Post checking OK.");
savedPost = repository.findById(linkTo);
if(savedPost != null){
Set<Post> linked = new HashSet<Post>();
linked.add(savedPost);
post.setLinkedPosts(linked);
}
template.save(post);
System.out.println("=====> [saveWithUser]: Saved OK!");
}
return savedPost;
}
When I call this method within a loop, sometimes it gets stuck (in one of the iterations) in the execution of template.save(post).
The same behaviour is observed when I call this method unitarily from a GUI.
PS: The findBy methods are not transactional.
I'm stuck on it since 2 weeks and I can't find a way to solve it :/
Thanks for any feedback.
Edit 1:
Logs produced by the method:
>>> Id created : IND6f770750-7834-40ae-a07e-fc81bbb3c657
>>> Date created : 2009Y09M20D
>>> People created : [People [id=PPLaf830449-b15c-4c71-b706-abd11492b825, name=Mary], People [id=PPLdf53d2c7-06b1-49c8-9b69-3b765d9b2ee6, name=Laptop]]
>>> Place created : Place [id=2918548, name=null]
Post checking OK.
PS: The iteration before the blocked one, it shows a normal log execution but nothing created in the DB
Edit 2:
And sometimes I get this error (always during the 2nd iteration while 1st shows normal logs but writes nothing on DB):
javax.transaction.RollbackException: Tx status is: STATUS_MARKED_ROLLBACK
I think I found the problem (but not yet the solution)
I removed all #Transactional annotations from my service methods (controllers and repositories are not marked as Transactional).
In the method createAndLink described in the main post I added transaction this way :
if(post != null && appuser != null){
Transaction tx = template.getGraphDatabaseService().beginTx();
//I kept the same code...
//...
tx.success();
tx.close();
}
Now, when I call this method from a controller A, the tx is of type Placebo. When I call it from a controller B, the tx type is a TopLevel.
I even made a test with calling the controller A method from the controller B (like in the example below) and it worked perfectly (with a TopLevel Tx). When I do the opposite way, the Tx is Placebo.
Controller A:
#RequestMapping(value="/newandlinksimilar/{linkedTo}", method=RequestMethod.POST)
public #ResponseBody boolean createAndLinkNewSimilar(#RequestBody Post post, #PathVariable String linkedTo){
Post created = null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (post!= null && !(auth instanceof AnonymousAuthenticationToken)) {
AppuserDetails userDetails = (AppuserDetails)auth.getPrincipal();
Appuser currentUser = appuserService.findByLogin(userDetails.getUsername());
created = postService.createAndLinkSimilar(currentUser, post, linkedTo);
}
return created;
}
Controller B:
#autowired
private ControllerA controllerA;
#RequestMapping("/init")
public ModelAndView init(){
//I create a new Post object "post" with dummy data
controllerA.createAndLinkSimilar(post,"XXXXXX");
//Or postService.createAndLinkSimilar(appuser,post,"XXXXXX");
return new ModelAndView("home");
}
Both tests are made from a GUI ajax call to the controller method.
I can't understand when and how Spring choose the type of the transaction?!

Session Variables and List Object not Updating Correctly

I should be able to figure this out, but I've been fighting with it for quite a while now.
I have a popup page that has several available requests that a user can select from. Based upon the page that the user is accessing, there could be one request or multiple requests available for that user. The single and multiple request are both saved on different session variables.
I need to know the single request that the user selected at the beginning of the process. It works fine except when the user is allowed to add multiple requests, the single request session variable is also updated.
For example, single request variable has "Florida"; then, the user reaches the multiple request page and adds GA and LA to the multiple request session variable. The single request variable is also updated to include GA and LA even though the flag is false and never reached that line. I don't want it to be updated. I need that single request to be available at all the time, so the user can see it if and when requested.
Here is a sample code where the issue is happening:
List<Request> temp = new List<Request>();
List<Request> mySearchRequest = new List<Request>();
List<Request> listSingleRequest = new List<Request>();
if (SessionWrapper.currentRequest.AvailableRequests != null)
{
mySearchRequest = (List<Request>)SessionWrapper.currentRequest.AvailableRequests;
}
if (SessionWrapper.currentRequest.MultipleRequests != null)
{
temp = (List<Request>)SessionWrapper.currentRequest.MultipleRequests;
var test = temp.Find(delegate(Request req) { return req.RequestId == id && req.Desc == description; });
// Checking if we have on the container already
if (mySearchRequest.Any(r => r.RequestId == id && r.Desc == description) == false)
{
mySearchRequest.Add(test);
if (SessionWrapper.currentRequest.SingleRequest == true && mySearchRequest.Count() == 1)
{
listSingleRequest.Add(test);
SessionWrapper.currentRequest.singleRequest = listSingleRequest ;
listSingleRequest = null;
}
}
}
//Set multiple request session here
Your help is greatly appreciated.
Thanks,
JF
After playing around with it almost all night, I was able to fix it. I am not sure if that is the most efficient way of doing it, but it works for now.
if (SessionWrapper.currentRequest.MultipleRequests != null)
{
temp = (List<Request>)SessionWrapper.currentRequest.MultipleRequests;
var test = temp.Find(delegate(Request req) { return req.RequestId == id && req.Desc == description; });
// Checking if we have on the container already
if (mySearchRequest.Any(r => r.RequestId == id && r.Desc == description) == false)
{
mySearchRequest.Add(test);
if (SessionWrapper.currentRequest.SingleRequestPage == true && mySearchRequest.Count() == 1)
{
foreach (var item in test)
{
//Create a new request object and add it to the list
Request request = new Request();
request.RequestId == item.RequestId;
request.Description == item.Description;
listSingleRequest.Add(request);
}
SessionWrapper.currentRequest.singleRequest = listSingleRequest ;
listSingleRequest = null;
}
}
}
if (SessionWrapper.currentRequest.singleRequest != null)
{
tempRequest = SessionWrapper.currentRequest.singleRequest.ToList();
foreach (var test in tempRequest)
{
Request request = new Request();
request.RequestId == item.RequestId;
request.Description == item.Description;
listSingleRequest.Add(request);
}
SessionWrapper.currentRequest.ViewRequest = listSingleRequest;
listSingleRequest = null;
}

Resources