Tumblelog by Soup.io
Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

January 09 2018

Django 2.0’da gelen yenilikler ve daha fazlası!

Django 1.11.x; Python 2.7’yi destekleyen son seridir. Django; 2.0 ile artık Python 3.4, Python 3.5 ve Python 3.6’ya destek verecek. Python 3.4 ile geliştirme planlıyorsanız Django 2.0 2019 Nisan’da geliştirme bırakıp üst serilere geçiş yapılacak. Çünkü Python 3.4 için 2019 Mart’da geliştirmeyi devam edilmeyecek.

 

Pdf halinde link : TIKLA

Use Bitcoin to Get Two Scoops of Django at 25% Off

BitCoin and Two Scoops of Django!

Like the title of this blog post says, for Bitcoin purchases we're offering a 25% discount for purchases of Two Scoops of Django. That puts the ebook version at $34.36 and the autographed hardcopy at $38.36. Pretty awesome, right? If you want to take advantage of this awesome deal, the Bitcoin discount is applied during checkout.

Combining the Bitcoin Discount With the Bulk Discount

Yes, the Bitcoin discount can be combined with bulk orders. So if you order 15 books or more, you get both the 20% bulk discount and the 25% bitcoin discount. That means each book is bought at $28.77 versus $47.95! Furthermore, bulk orders are shipped free to anywhere in the world. This makes it an incredible deal for companies, organizations, and user groups.

Stay tuned!

January 08 2018

On degrees

Lately there’s been a recurring discussion on various social-media outlets about the value and/or necessity of academic degrees to a career in programming. I’ve jumped into a few such threads on Twitter, but 140-character or (now) 280-character chunks of commentary don’t really let me do justice to the topic. Luckily, this is my blog and it obeys my rules and I can use as many characters as I like. So here’s a fuller and ...

Read full entry

pytest-randomly history

Hall of history

My plugin pytest-randomly was recently moved into the pytest-dev organization on GitHub, making it a bit “more official” as a pytest plugin. Thanks to Bruno Oliveira for suggesting it, Florian Bruhin and Bruno for approving it on the pytest-dev mailing list, and Gordon Wrigley for helping with its development.

In celebration I thought I’d explain a bit more of the background behind it. pytest-randomly really combines two functions:

  1. Controlling the random seed between test runs, which is useful when using a tool like Factory Boy to generate test data. By allowing the same seed to be used again, failures can be debugged. See more in my blog post on it.
  2. Reordering tests randomly, to discourage order-dependency, which can be common with certain fixture patterns touching global state like a database

For YPlan, we needed random seed control. We added Factory Boy to shrink the test code needed to set up Django model instances, and to get more value from the tests by covering a wider range of cases between runs. We were using nose at the time, and implemented a plugin to reset the seed at the start of each test and a flag to control in just a few lines of code.

Later on we added the test reordering code, due to problems with Django’s setUpTestData. This hook allows you to perform setup once at the start of all the tests in a test class, and keep it between the individual test functions with rollback at the database layer. The benefits can be huge as you can perform the same setup for a bunch of tests once instead of tens of times. The problem we encountered was mismatch between python and the database. Consider these tests:

class MyTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        super().setUpTestData()
        # DB rolled back to this state between tests
        cls.book = Book.objects.create(name='Verily, A New Hope')

    def test_1(self):
        self.book.name = 'The Empire Striketh Back'
        self.book.save()
        do_some_assertions()

    def test_2(self):
        do_some_other_assertions()

The problem is that under the written test ordering, when test_2 runs its self.book object will be inconsistent between python and the database. The database has been rolled back to the state from setUpTestData, but on the MyTests object, self.book.name will still be 'The Empire Striketh Back' - there is no process to undo the changes from test_1 in Python. When this causes test failures it’s a bad case of action-at-a-distance, with state leaking between tests.

This can be avoided by never caching model instances on the test cases, or always copy.deepcopy()ing them before modifying them inside a test function, but both are easy to forget. And there is always other global state that can be modified and not reset, like the contents of any module (yay Python 😁).

Order randomization is a way of protecting against this problem. If tests leak state and pass on one run, it’s unlikely they’ll pass on the next run as the order will be re-randomized.

We implemented randomization of order on nose by taking some existing code from ‘Massive Wombat’ (?) on Google Code and Nick Loadholtes on GitHub, merging it with our random seed reset plugin, and tidying it up to work with all the kinds of tests we had. After a while I had the chance to open source it as nose-randomly. Naturally, when we moved to pytest, this was rebuilt as pytest-randomly 👌

The main development on pytest-randomly since has been to make it reset the random generators used by some popular libraries, and to make it work with all the kinds of test items that pytest supports (sometimes they don’t even live in a module!).

I’d encourage everyone to add randomization to their test runs, especially on large projects where the tests might have some dark corners. If you have any suggestions for pytest-randomly, its GitHub issues are always open.

January 05 2018

New year, new stuff

H appy 2018 everyone! Here's a little summary of the past Evennia year and what is brewing.

(Evennia is a Python server- and toolbox for creating text-based multiplayer games (MU*)).

The biggest challenge for me last year Evennia-wise was the release of Evennia 0.7. Especially designing the migration process for arbitrary users migrating the Django auth-user took a lot of thought to figure out as described in my blog post here. But now 0.7 is released and a few initial minor adjustments could be made after feedback from daring pilot testers. The final process of migrating from 0.6 to 0.7 is, while involved, a step-by-step copy&paste list that has worked fine for most to follow. I've gotten far fewer questions and complains about it than could be expected so that's a good sign.

Working away on the boring but important behind-the-scenes stuff made me less able to keep up with more "mundane" issues and bugs popping up, or with adding new "fun" features to existing code. Luckily the Evennia community has really been thriving this year; It feels like new users pop up in the support channel all the time now. The number of pull requests both fixing issues and offering new features and contribs have really picked up. A bigger part of my time has been spent reviewing Pull Requests this year than any other I think. I would like to take the opportunity to thank everyone contributing, it's really awesome to see others donating their time and energy adding to Evennia. The Hacktoberfest participation was also surprisingly effective in getting people to create PRs - I have a feeling some were just happy to have an "excuse" for getting started to contribute. We should attend that next year too.

One thing we added with 0.7 was a more formal branching structure: Evennia now uses fixed master and develop branches, where master is for bug-fixes and develop is for new features (things that will eventually become evennia 0.8). This is simple but enough for our needs; it also makes it easier to track new from old now that we are actually doing releases.

Now that Twisted is at a point where this is possible for us to do, we also now have a sort-of plan for finally moving Evennia to Python 3. I won't personally be actively working on it until after 0.8 is out though. I don't expect both Evennia 0.8 and 0.9 (which will be pure py3) to get released this year, but we'll see - so far contributors have done all the work on the conversion.

At any rate, this coming year will probably be dominated by catching up on issues and edge cases that are lining our Issue tracker. One side effect of more newcomers is more eyes on the code and finding the creaky-bits. At least for me, most of my Evennia-time will be spent resolving bugs and issues. The fun thing is that unlike previous years this is not only up to me anymore - hopefully others will keep helping to resolve issues/bugs to broaden our bandwidth when it comes to keeping Evennia stable. The faster we can handle the backlog of issues the faster we can focus on new shiny features after all.

Finally, a continued great thank you to those of you contributing to the Patreon. Even small donations have a great encouraging value when working on something as niche as a Python MU* game server in 2018 - thanks a lot!

TemplateTag to call a method / function WITH arguments

Callmethod - TemplateTag to call a method on an object with arguments from within a template

{% callmethod hotel.room_price_for_night night_date="2018-01-02" room_type=room_type_context_var %}
    ## equals ##
>>> hotel.room_price_for_night(night_date="2018-01-02", room_type="standard") #Assuming "standard" is the value of room_type_context_var

Django doesn't allow calling a method with arguments in the template to ...

2018 New Years Resolutions

Lasergun Light Painting

Happy New Year!

The last time I wrote down resolutions was way back in 2014. I had done it for many years at that point, dating back to even before my old blog. Somehow I fell out of what I consider a positive habit. Well, it's time to pick it up again!

So here are my resolutions for 2018:

  1. Weight down to 160.
  2. Work out for 60 minutes a day. I got lazy in the last year.
  3. Start martial arts again. Because of knee and ankle injuries, Capoeira is probably right out. Already up Kali/Escrima under Guro Mestre Xingú instead.
  4. Write at least 3 books (last year we did 5 books, so this is doable!). Out of those, one will be about coding in some way.
  5. Blog at least once a month, about anything. Python, Django, serverless coding, martial arts, whatever. And with this post, January is done!
  6. Release some coding projects I can't talk about yet.
  7. Travel outside the USA. That looks to be a trip to Colombia to speak at PyCon Colombia! If you are in South America, please meet me (and Audrey) there! I'll be sharing more details soon. :-)

note: The photo is from a light painting session I did with Audrey at the start of last year.

January 03 2018

Elm & Django #1

Here is a simple solution to run Elm code within a Django template. This could be used to handle the full frontend or just to embed a "widget" - like a search bar - via Elm.

January 01 2018

Caktus Blog Best of 2017

With 2017 now over, we highlight the top 17 posts published or updated on the Caktus blog this year. Have you read them all?

  1. Using Amazon S3 to Store your Django Site’s Static and Media Files: Our most popular blog post was updated in September 2017 with new information. Learn how to use Amazon S3 to serve static and media files and improve site performance.
  2. A Production-ready Dockerfile for Your Python/Django App: Docker provides a solid way to containerize an app. This blog post includes a Dockerfile ready for your use plus instructions on how to use it in a project.
  3. Python Type Annotations: Type annotation support in Python helps developers avoid errors. Read this post for a quick overview on how to use them.
  4. Digging Into Django QuerySets: Learn how to use the Django shell with an example app to perform queries.
  5. Hosting Django Sites on Amazon Elastic Beanstalk: We use AWS Elastic Beanstalk for deploys and autoscaling. This post introduces the basics and how to use it with Python.
  6. SubTests are the Best: Good tests are important to good code, but what makes a good test? Three factors are detailed in this post, which was also presented as a talk at PyOhio 2017 and can be watched on YouTube.
  7. Writing Unit Tests for Django Migrations: Another all-time top blog post which received an update this year, with a walkthrough demonstrating how to write thorough tests for multiple versions of Django.
  8. Managing Your AWS Container Infrastructure with Python: Introducing CloudFormation and Troposphere as tools to host and manage Python apps on AWS.
  9. New Year, New Python: Python 3.6: Highlights from the Python 3.6 release, including secrets, new string interpolation methods, variable type annotations, and more.
  10. Advanced Django File Handling: Customize Django’s file handlers for more flexibility. This post shows you how.
  11. 5 Ways to Deploy Your Python Web App in 2017: Part of our PyCon 2017 Must See Series, this summary also includes the video of the talk at PyCon. Take a look at a live app deployment with ngrok, Heroku, AWS Lambda, Google Cloud Platform, and Docker.
  12. Python Tool Review: Using PyCharm for Python Development - and More: One of our developers reviews the PyCharm IDE for Python. Learn more about how it’s used at Caktus in this interview with our developers (from JetBrains).
  13. Opening External Links: Same Tab or New?: An exploration of the debate around how external links should open, with perspectives from marketing, UX, web development, and users.
  14. Building a Custom Block Template Tag: A walkthrough of how to build a block tag, with references to relevant Django documentation.
  15. 3 Reasons to Upgrade to the Latest Version of Django: For business stakeholders new to website development, we offer three reasons why upgrading the technology behind the site should be considered a necessity.
  16. From User Story Mapping to High-Level Release Plan: The user story map created as part of a discovery workshop is an excellent tool to use in writing the first release plan for a development project. Find out why in this post.
  17. How to Make a jQuery: Recreate the most helpful parts of jQuery to learn how to develop without it.

Going into 2018

What were your favorite posts? What topics did you find most interesting or helpful? What are you hoping to learn about in 2018? Let us know in the comments or on Twitter what you’d like to see more of in the coming year.

December 30 2017

Reset Postgres Sequences On Every Migrate

If you create alot of data via fixtures or by inserting the pk you will more than likely see alot of issues with the sequences being out in postgres when creating new records.

Similar to: Foo with the pk(x) already exists

This you have to fix by updating the ...

December 29 2017

templatetags - get youtube video id

Returns Video_ID extracting from the given url of Youtube.

December 28 2017

December 23 2017

December 20 2017

Building Modern Django Web Applications with React and Django Rest Framework

In nutshell, in this tutorial we'll look at how to build a modern (SPA: Single Page Application) CRUD web application using Django and React.js (instead of Django built-in templates engine). We'll use Django Rest Framework to build an example API, react-router-dom for routing the front-end app, Axios for making HTTP calls (GET, POST, PUT and DELETE etc.) to the Rest API endpoints, Redux for managing the app's global state and finally Webpack to bundle the assets

This tutorial will cover how to serve the React app using the Django server and how to allow the React app to communicate with the Django server over its Rest API endpoints

When building a modern web application with tools such as Django and React in our case, React will take care of rendering the view layer of your app's architecure and Django will be used for communicating with the database and exposing a CRUD REST API. You can have completly separate front-end and back-end or you can also make Django serve the first page where the React app will be mounted (we'll follow this second approach in this tutorial).

The communication between React and Django will be made using HTTP/Ajax requests to the rest API endpoints (we'll use Axios but you can also use the modern browser's fetch API or even the old XMLHttpRequest interface or a wrapper library around it).

We'll use the modern front-end tools such as Webpack and Babel for transpiling (compiling from JavaScript 2015 (ES6) to JavaScript 5) and bundling React source code into one single bundle. Don't worry though, we'll be using create-react-app, an official React CLI-based tool that allows you to generate and locally serve React projects (among other features) without going through the hassle of Webpack configuration or any complex JavaScript configuration.

In the back-end we'll create a simple Django API with Django Rest Framework.

In the front-end we'll consume the API (with Axios and Promises) to fetch data and then render it. We'll also add routing using the React router version 4 and Redux for managing the global state of the application.

Setting Up the Development Environment

This tutorial assumes you have a development environment with Python and NodeJS installed. You can find the binaries and the instructions to install both platforms on their corresponding official websites.

It's recommended that you use python virtualenv. A tool that allows you to create isolated virtual environments for Python packages so you can install and use different versions of the same library (for different projects) and avoid any conflicts. You can install virtualenv using the virtualenvwrapper.

Installing Django

First, let's start by creating and activating a new virtual environment for our project dependencies:

virtualenv myenv
source myenv/bin/activate

Next you'll need to install Django using the pip package manager:

pip install django

Creating a Django Project

After installing Django, you'll be able to create a Django project using django-admin

django-admin startproject django-react-crud

If you migrate your database and serve your app, at this point, with:

python manage.py migrate
python manage.py runserver

You should have the famous It Worked! welcome page when you navigate with your web browser to http://127.0.0.1:8000.

If everything works as expected. The next step it to integrate Django Rest Framework and React.

Introduction to React

React is a JavaScript library for building modern user interfaces, developed and used internally by Facebook. It's steadliy growing in popularity among developers worldwide.

React is a declarative and component-based library, it can be rendered in the server side (for boosting load time performance and making your app SEO friendly i.e crawlable by search engines) and can be used to build native mobile applications with React Native

Installing create-react-app

Create React App is a CLI-based utility to generate React apps without the hassle of Webpack and Babel configuration. That doesn't mean these tools are not used but they are just taken care of, so you can focus on building your React app instead of setting up the build environments.

npm install -g create-react-app

What's Webpack?

Webpack is a modern tool for module bundling. It allows web developers to bundle all dependencies (JS scripts, CSS styles and images) into small bundles which reduces the roundtrips to servers (for getting assets).

At its core, webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into one or more bundles. -- https://webpack.js.org/concepts/

Pleas note that if you want to customize the Webpack configuration files of your React project you need to eject the configuration of your project using npm run eject.

Tracking the Generated Webpack Bundles

Webpack generates the bundles for your app with hashed filenames so we need a way to track these filenames automatically without having to manually change your template to include the correct filenames, particularly in the development phase where they frequently change.

webpack-bundle-tracker is a Webpack plugin that outputs a JSON file (webpack-stats.json) containing the information we are looking for i.e the names of the bundles.

So head back to your terminal or command line, navigate inside your React project then run the following command to install webpack-bundle-tracker:

npm install webpack-bundle-tracker --save-dev

Next you need to eject the Webpack configuration files so you can include the plugin to your configuration with:

npm run eject

You'll have a config folder with different configuration files for development and production

Creating the Front-end with React

By issuing a few commands you can generate a React app and start building your next app without going through any Webpack configuration.

Next create the React app inside your Django project root folder

npm install -g create-react-app
create-react-app frontend

If the command fails you can try with sudo to execute the install command with the super user priviliges.

You can start the application with:

npm run start

This will start the Webpack development server which serves your app locally with hot loading i.e when you change anything in the source code the server reloads your app automatically.

Open config/webpack.config.dev.js then add:

var BundleTracker  = require('webpack-bundle-tracker');
module.exports = {

    plugins: [
          new BundleTracker({path: "../", filename: 'webpack-stats.json'}),
    ]
}

This will import the bundle tracker plugin and add it to the list of Webpack plugins. We set the path to ../ to point to the root folder of your Django project and the filename to webpack-stats.json.

Next open config/webpack.config.prod.js then add:

var BundleTracker  = require('webpack-bundle-tracker');
module.exports = {

    plugins: [
          new BundleTracker({path: "../", filename: 'webpack-stats.json'}),
    ]
}

This will setup the bundle tracker to generate a file named webpack-stats.json for the bundles information in production.

Create a REST API with Django Rest Framework

Django REST framework is a powerful and flexible toolkit for building Web APIs. Some reasons you might want to use REST framework: The Web browsable API is a huge usability win for your developers. Authentication policies including packages for OAuth1a and OAuth2. Serialization that supports both ORM and non-ORM data sources. Customizable all the way down - just use regular function-based views if you don't need the more powerful features. Extensive documentation, and great community support. Used and trusted by internationally recognised companies including Mozilla, Red Hat, Heroku, and Eventbrite. --http://www.django-rest-framework.org/

Since the communication between React and Django happens over an API we'll need to create a Django API using the Django Rest Framework. But let's start with the development environment

Create a Django Template for Serving the React Front-end

Let's first create the Django template (and its related route and view) where we are going to mount the React app. We need to create a template in templates/main.html after making sure you have configured Django to find your template files.

In project's settings.py, under TEMPLATES array add:

TEMPLATES = [
    {
        # ... 
        'DIRS': [os.path.join(BASE_DIR, "templates"), ],
        # ... 
    },
]

Next let's put some content in the template:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Django + React CRUD</title>
  </head>
  <body>
    <div id="root">
     This is where React will be mounted
    </div>

  </body>
</html>

Once you have done that. Go ahead and create a view and an URL to render the template. Open your project's urls.py file then wire this template to the main URL of your app i.e '^' using the generic TemplateView class:

from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView

urlpatterns = [
    ##
    url(r'^', TemplateView.as_view(template_name="main.html")),
    ##
]

Integrating Django with React

To integrate the Django and the React applications we need to serve the front-end (i.e the React app) using the Django server. The process is simple but we have one problem though! Webpack generates the React bundles dynamically and with hashed filenames so we'll need to use django-webpack-loader--a django application which injects the dynamically generated bundles using the <script> and <link> tags into the Django templates. Using the Webpack loader Django will be able to know which bundle to load in the template.

You'll first need to install the application with pip:

pip install django-webpack-loader

Next you need to add the application (webpack_loader) into INSTALLED_APPS in your project' settings.py file:

Then add the Webpack loader configuration object in settings.py

WEBPACK_LOADER = {
    'DEFAULT': {
            'BUNDLE_DIR_NAME': 'bundles/',
            'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
        }
}

Now you need to change tha main template by adding the following changes:


{ % load render_bundle from webpack_loader % }

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Django + React CRUD</title>
  </head>
  <body>
    <div id="root">
     This is where React will be mounted
    </div>
    { % render_bundle 'main' % }
  </body>
</html>

The render_bundle tag takes 'main' as an argument and renders the script tag for the main bundle.

Open your React src/App.js file then add these changes:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Welcome to Django</h1>
        </header>
        <p className="App-intro">
            A React app with a Django backend
        </p>
      </div>
    );
  }
}

export default App;

Now you need to start your Webpack server and your Django local development server then navigate to http://localhost:8000/ with your wen browser. You should be able to see the React app running at this address.

Fixing Webpack Hot Reloading

Since we have served the Webpack bundle from the Django server the Webpack dev server will not be able to send XHR requests to React URLs to reload when source files change. So open config/webpackDevServer.config.js then add the following setting:

headers: {
  'Access-Control-Allow-Origin': '*'
},

This tells the Webpack server to accept requests from all origins including http://localhost:8000.

Also make sure to set publicPath and publicUrl to 'http://localhost:3000' in config/webpack.config.dev.js.

That's all you need to do to integrate React and Django for the approach we have followed. In the next tutorial we'll add React routing using react-router-dom then we'll see how to use Redux to manage the app global state. Meanwhile if you have any problems integrating React with Django feel free to post a comment below and I will be glad to help you!

Conclusion

We have seen how to create a React front-end for Django web apps using the Create React App project generator and how to send http requests from React to Django.

REST API Basics with the Django REST Framework

This post is the same as the p...

December 15 2017

December 09 2017

December 08 2017

December 01 2017

November 24 2017

Serializer/Deserializer with utf-8/timezone support

Sorry, this snippet only tested on Django ver.2.0rc1.

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.

Don't be the product, buy the product!

Schweinderl