Getting Django setup on Windows1. Install Python3.4 as default path. (It should be "C:\Python34"). 2. Open cmd.exe program on Windows and run the following commands: set PATH=%PATH%;C:\Python34;C:\Python34\Scripts pip install django python C:\Python34\Lib\site-packages\django\bin\django-admin.py startproject mysite cd mysite python manage.py syncdb (Follow prompts to setup an initial db. remember the user you used here.) python manage.py runserver 3. You are ready to django! Open your browser http://127.0.0.1:8000 to verify. Or login into http://127.0.0.1:8000/admin with the user you setup above. What's next? Explore django with a guided tutorial here: https://docs.djangoproject.com/en/1.6/intro/tutorial01 Learn Python in 5 min http://www.quora.com/How-do-I-find-a-good-Django-tutorial-for-beginners InstallationVia Laravel InstallerFirst, download the Laravel installer using Composer.
Make sure to place the ~/.composer/vendor/bin directory in your PATH (or C:\%HOMEPATH%\AppData\Roaming\Composer\vendor\bin if working with Windows) so the laravel executable is found when you run the laravel command in your terminal.Once installed, the simple laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new blog would create a directory named blog
containing a fresh Laravel installation with all dependencies
installed. This method of installation is much faster than installing
via Composer.Via ComposerThe Laravel framework utilizes Composer for installation and dependency management. If you haven't already, start by installing Composer.Now you can install Laravel by issuing the following command from your terminal:
This command will download and install a fresh copy of Laravel in a new your-project-name folder within your current directory.If you prefer, you can alternatively download a copy of the Laravel repository from GitHub manually. Next run the composer install
command in the root of your manually created project directory. This
command will download and install the framework's dependencies.PermissionsAfter installing Laravel, you may need to grant the web server write permissions to theapp/storage directories. See the Installation documentation for more details on configuration.Serving LaravelTypically, you may use a web server such as Apache or Nginx to serve your Laravel applications. If you are on PHP 5.4+ and would like to use PHP's built-in development server, you may use theserve Artisan command:
By default the HTTP-server will listen to port 8000. However if that
port is already in use or you wish to serve multiple applications this
way, you might want to specify what port to use. Just add the --port
argument:
Directory StructureAfter installing the framework, take a glance around the project to familiarize yourself with the directory structure. Theapp directory contains folders such as views , controllers , and models . Most of your application's code will reside somewhere in this directory. You may also wish to explore the app/config directory and the configuration options that are available to you.Local Development EnvironmentIn the past, configuring a local PHP development environment on your machine was a headache. Installing the proper version of PHP, required extensions, and other needed components is time consuming and confusing. Instead, consider using Laravel Homestead. Homestead is a simple virtual machine designed for Laravel and Vagrant. Since the Homestead Vagrant box is pre-packaged with all of the software you need to build robust PHP applications, you can create a virtualized, isolated development environment in seconds. Here is a list of some of the goodies included with Homestead:
RoutingTo get started, let's create our first route. In Laravel, the simplest route is a route to a Closure. Pop open theapp/routes.php file and add the following route to the bottom of the file:
Now, if you hit the /users route in your web browser, you should see Users! displayed as the response. Great! You've just created your first route.Routes can also be attached to controller classes. For example:
This route informs the framework that requests to the /users route should call the getIndex method on the UserController class. For more information on controller routing, check out the controller documentation.Creating A ViewNext, we'll create a simple view to display our user data. Views live in theapp/views directory and contain the HTML of your application. We're going to place two new views in this directory: layout.blade.php and users.blade.php . First, let's create our layout.blade.php file:
Next, we'll create our users.blade.php view:
Some of this syntax probably looks quite strange to you. That's
because we're using Laravel's templating system: Blade. Blade is very
fast, because it is simply a handful of regular expressions that are run
against your templates to compile them to pure PHP. Blade provides
powerful functionality like template inheritance, as well as some syntax
sugar on typical PHP control structures such as if and for . Check out the Blade documentation for more details.Now that we have our views, let's return it from our /users route. Instead of returning Users! from the route, return the view instead:
Wonderful! Now you have setup a simple view that extends a layout. Next, let's start working on our database layer.Creating A MigrationTo create a table to hold our data, we'll use the Laravel migration system. Migrations let you expressively define modifications to your database, and easily share them with the rest of your team.First, let's configure a database connection. You may configure all of your database connections from the app/config/database.php
file. By default, Laravel is configured to use MySQL, and you will need
to supply connection credentials within the database configuration
file. If you wish, you may change the driver option to sqlite and it will use the SQLite database included in the app/database directory.Next, to create the migration, we'll use the Artisan CLI. From the root of your project, run the following from your terminal:
Next, find the generated migration file in the app/database/migrations folder. This file contains a class with two methods: up and down . In the up method, you should make the desired changes to your database tables, and in the down method you simply reverse them.Let's define a migration that looks like this:
Next, we can run our migrations from our terminal using the migrate command. Simply execute this command from the root of your project:
If you wish to rollback a migration, you may issue the migrate:rollback command. Now that we have a database table, let's start pulling some data!Eloquent ORMLaravel ships with a superb ORM: Eloquent. If you have used the Ruby on Rails framework, you will find Eloquent familiar, as it follows the ActiveRecord ORM style of database interaction.First, let's define a model. An Eloquent model can be used to query an associated database table, as well as represent a given row within that table. Don't worry, it will all make sense soon! Models are typically stored in the app/models directory. Let's define a User.php model in that directory like so:
Note that we do not have to tell Eloquent which table to use.
Eloquent has a variety of conventions, one of which is to use the plural
form of the model name as the model's database table. Convenient!Using your preferred database administration tool, insert a few rows into your users table, and we'll use Eloquent to retrieve them and pass them to our view.Now let's modify our /users route to look like this:
Let's walk through this route. First, the all method on the User model will retrieve all of the rows in the users table. Next, we're passing these records to the view via the with method. The with method accepts a key and a value, and is used to make a piece of data available to a view.Awesome. Now we're ready to display the users in our view! Displaying DataNow that we have made theusers available to our view, we can display them like so:
You may be wondering where to find our echo
statements. When using Blade, you may echo data by surrounding it with
double curly braces. It's a cinch. Now, you should be able to hit the /users route and see the names of your users displayed in the response.This is just the beginning. In this tutorial, you've seen the very basics of Laravel, but there are so many more exciting things to learn. Keep reading through the documentation and dig deeper into the powerful features available to you in Eloquent and Blade. Or, maybe you're more interested in Queues and Unit Testing. Then again, maybe you want to flex your architecture muscles with the IoC Container. The choice is yours! Deploying Your ApplicationOne of Laravel's goals is to make PHP application development enjoyable from download to deploy, and Laravel Forge provides a simple way to deploy your Laravel applications onto blazing fast servers. Forge can configure and provision servers on DigitalOcean, Linode, Rackspace, and Amazon EC2. Like Homestead, all of the latest goodies are included: Nginx, PHP 5.6, MySQL, Postgres, Redis, Memcached, and more. Forge "Quick Deploy" can even deploy your code for you each time you push changes out to GitHub or Bitbucket!On top of that, Forge can help you configure queue workers, SSL, Cron jobs, sub-domains, and more. For more information, visit the Forge website. ......................................................................................................................................... All the Blade Template Commands
So to start.. we want to add/edit the content of our homepage. We can do this by going in to /app/routes.php. You will see that currently the route is hardcoded to return View::make('hello'). We could then simply change the view file.. but long term this just isn't going to fly. So comment this out (for the purpose of the tutorial - later you could remove completely) and add return HomeController::showWelcome(). You should now have something that looks like this: 1. Route::get( '/' , function () 2. { 3. return HomeController::showWelcome(); 4. //return View::make('hello'); 5. }); To start with now, we will set our logic inside the controller - but later in the tutorial we will move this in to a model. Change your showWelcome method to this: 01. public static function showWelcome() 02. { 03. 04. //$cheese = Test::getCheese(); 05. 06. $data = array ( 07. 08. 'cheese' => 'cheese value' 09. ); 10. 11. return View::make( 'hello' , $data ); 12. } OK.. so the first bit... ignore the commented out line for now.. we will come back to it. The array called $data... this is where we can set all data that is passed to the view file. And you can see that for now I've hardcoded the value of 'cheese' to 'cheese value'... we will move this over to the model shortly. Finally, we now tell the method to return a view, and we pass in to it our $data array. If we go in to /app/views/hello.php now... you can add a echo $cheese; statement somewhere amongst the main html content (obviously wrapped in PHP tags). And now when you refresh yourdomain.com/public you should see the usual splash page.. but now with added cheese. OK.. so we're in a much stronger position now... but now we want to ensure that our business logic is performed outside of the controller... as we don't want big fat ugly controllers. We're now going to set it so that cheese value is returned from a model. So to start create a new file called Test.php inside of /app/models and then add this code to it: 01. class Test { 02. 03. 04. public static function getCheese() { 05. 06. return "cheeeese" ; 07. } 08. 09. } If we now go back to our controller HomeController.php, uncomment the uncommented line $cheese = Test::getCheese(); ... then change 'cheese value' to the var $cheese... like so: 1. $data = array ( 2. 3. 'cheese' => $cheese 4. ); That concludes this basic tutorial... obviously there is a lot more to learn about Laravel, but this tutorial at least (I hope) shows you how to setup a very basic page in Laravel. Thanks for reading! ............................................................................................. This tutorial will walk us through:
Getting our Database ReadyTo get our authentication working, we will need to have a database and users to login with.Database SetupSet up your database and user. Assign that user to the database and make sure you update your settings inapp/config/database.php .MigrationsMigrations are a way we can manipulate our database within our codebase. This means we don’t have to get our hands dirty by doing any SQL commands or messing around inside a tool like phpmyadmin. For more information and the benefits of migrations, see the official docs.Migrations are very easy to create. The easiest way to create a migration will be to use the great artisan command line interface created by Taylor Otwell. To create the migration, via the command line, in the root folder of your application, simply type: php artisan migrate:make create_users_table ––create=users This will automatically create a migrations file inside of your app/database/migrations folder. Let’s take a look at the newly created file.
Laravel generates the core of the migration file for you and the
–create command will let the migration create the table for you. It will
create a table for you with an id field and the timestamps field. This
will make created_at and updated_at fields. Now we use the Schema Builder to create our users table.
Now this migration file will be responsible for creating the users table and also destroying it if needed. To run the migration and create our user table, use the command line again and run:php artisan migrate Just like that, the command will use the up() function and bam! We have our users table with all the columns we wanted.
Reverting Migrations: Now if you wanted to rollback migrations, we could use
Now that we have our table, lets create sample users.php artisan migrate:rollback or php artisan migrate:reset .
SeedingSeeding is the technique of filling our database with sample data so we can test and create our applications. It really does make building applications much easier. For seeder files, we won’t be using artisan. We’ll make these the good old fashioned way… New file. In yourapp/database/seeds folder, create a file called UserTableSeeder.php .
We will create a user and all of the above is pretty self explanatory
aside from password. We will use Laravel’s Hash class to create a
secure Bcrypt hashing of our password. This is always a good practice to
hash our password and to read more about Laravel security, check out
the docs. Now that we have created our file, we need to Laravel to call it. Inside the app/database/seeds/DatabaseSeeder.php , add the line $this->call('UserTableSeeder'); .
Once we’re done with our seeder file, we can inject that user into our database using:php artisan db:seed The ApplicationNow that we have a database, a table thanks to migrations, and a user thanks to seeding, we can build the authentication system. We will need to create routes, controllers, and views for our form.RoutesIn Laravel, our routes file dictates the lay of the land in our application. We will define 2 routes for our login, one for the http get to show the form, and one for the http post request to process the form. Laravel let’s us define routes based on HTTP request types and this helps to organize our application and how a user interacts around the site. For more info on this: show link. Add the following routes we need in ourapp/routes.php file:
Now if we go to our application in our browser and go to www.example.com/login, we will get an error because we haven’t defined the HomeController@showLogin function yet. Let’s do that. ControllerIn ourapp/controllers directory, Laravel should already come with a HomeController.php and a BaseController.php. Inside our HomeController.php, we are going to create the two functions we need. Add these two.
For now, we will only deal with the function to show the form.ViewThe easiest part of this process will be creating our login view. In theapp/views folder, create a file called login.blade.php . The .blade.php extension lets Laravel know that we will be using its Blade Templating system.
When someone submits the form, it posts to the HomeController@doLogin function. Let’s validate the information and process the form. If there are validation errors, they will be redirected here and the email input will already be filled in with their old input. Errors will also show if there are any. Processing the FormBack in our HomeController.php, let’s build out ourdoLogin() function. We have to validate the information sent to make sure that we have an email and a password. Both fields are required.
We use the Auth class to authenticate a user. Auth::attempt() will check the plaintext password against the hashed password we saved in our database.Try the login: Let’s try to login with whatever we put in our app/database/UserTableSeeder.php file. In our case:
Auth::user()->email; .
If the authentication is not successful, we will be kicked back to the
login form with errors and the old email input to populate the form.LogoutLogging out is a simple matter. We’ll need a new route and a new function.Add this route for logout.
Ideally, this route would be a
For logout, we will flush and clean out the session and then redirect
our user back to the login screen. You can change this to redirect a
user wherever you would like. A home page or even a sad goodbye page.POST route for security
purposes. This will ensure that your logout won’t be accidentally
triggered. http://stackoverflow.com/questions/3521290/logout-get-or-post
Also, to handle this as a POST , you will have to handle your link differently. You’ll have to create a POST request to your logout route.
Now that you have the route and the function, you can create a logout button by using the Laravel URL helper.
Bam!Now going to your login page, www.example.com/login and submitting the login form will provide validation, authentication against a user in the database, and a little more understanding of how Laravel makes things like building an authentication system easier. We’ll be doing a lot more writeups on Laravel, so sound off in the comments if you have questions or anything else you want to see.
Edit Updated the doLogin() function and the view to pass back errors and handle Auth correctly with Hash::check(). Edit #2 Changed back to the Auth::attempt() login method. Edit #3 Cleaned up and commented code examples. Provided code for download. Edit #4 Added logout. Edit #5 Upgraded user migration to work with Laravel 4.1.26
----------------------------------------------------------------
Q.....This question may seems a little bit silly, but what the heck. I started to learn Python. I know basic syntax, etc. When I work with HTML, PHP, etc., I simply write code, put it inside .html or .php file and double click this file. Then my code runs. I can work with databases and other stuff - it's just simple. But how does Python work? I'm working inside Eclipse or Python command line and I can run this code, but what if I want make website with Python for example? I don't think it's like I put .py file on my server, so what I need to do? I understand I need to install Python on my webserver through some server command line (I've never used it, but I will find some tutorials day I will need it) but what's next? How can I combine my Python knowledge with HTML, CSS, PHP, etc.? Python may also be used to create desktop apps, what then? Can I export .exe file with Python code or what? Any links with content describing my concerns are welcome! http://programmers.stackexchange.com/questions/107922/how-does-python-work ANS................. When I work with HTML, PHP, etc., I simply write code, put it inside .html or .php file and double click this file. Then my code runs.Exactly the same way. Double-click a .py file and your code runs. I'm working inside Eclipse or Python command line and I can run this code, but what if I want make website with Python for example?You usually use Apache to host a web site. You usually use mod_wsgi to run Python inside Apache. This is exactly like using mod_php to run PHP inside Apache.Exactly the same. I don't think it's like I put .py file on my server,False. You do put .py files on your server. How else could it possibly work? so what I need to do? I understand I need to install Python on my webserver through some server command line (I've never used it, but I will find some tutorials day I will need it) but what's next?You need mod_php to run PHP. You need mod_wsgi to run Python. So if I made some website with Python, then my user will see my index.py file when he comes to my server?You could do that. It would be fairly silly, however. Usually, you set up mod_wsgi so that it executes your .py file, and your .py file creates the HTML page.This parallels the way mod_php executes the .php file to create an HTML page.
Or can I use Python code inside html like with php wrapped inside
No. You put the HTML inside the Python. How can I combine my Python knowledge with html, css, php etc?Use a web framework that supports Python, such as Django. Python may also be used to create desktop apps, what then? Can I export .exe file with Python code or what?Python is typically executed by an interpreter, so it's easy to use interactively and you can see results of your changes almost immediately. A Python program can also be packaged up into a stand-alone executable; more on how to do that here. Django is a free web framework written in python. It's very to use!Let's create a blog in less then 10min!1. First create a projectdjango-admin.py startproject blog Switch to folder "blog"Start the dev server./manage runserver 8000 Type: http://127.0.0.1:8000 in browser2. Create a file "models.py"Create a modelfrom django.db import models class Blog(models.Model): title = models.CharField(max_length=32) date = models.DateTimeField(auto_now_add=True) text = models.TextField() 3. Setup your database settingsEdit the file "settings.py"DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'test', # Or path to database file if using sqlite3. 'USER': 'test', # Not used with sqlite3. 'PASSWORD': 'password', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } 4. "Install" the blog modelsAdd "blog" to INSTALLED_APPSINSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'blog', #<------------------------------- # Uncomment the next line to enable the admin: #'django.contrib.admin', ) 5. Create a templatesCreate folder "templates".Switch to folder "templates". Create file "index.html"<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>My Blog</title> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> </body> </html6. Setup the templates path Edit "settings.py" file. Import os at the top Add path to TEMPLATES_DIRS TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(os.path.dirname(__file__),'templates'), # creates a absolute path ) 7. Create the blog tablesRun "./manage syncdb"
It will create the blog tables.
|
Search Google
Sunday, 19 April 2015
How does Python work?
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment